Java solution with explanation


  • 0
    T

    Use the hashmap to store <content, filepaths> pairs.
    For every given path, split it by a white space so that the directory name is the first element and each other element stands for a filename(content).
    If map.contains(content), append this new file path to the corresponding filepaths.
    Else put the new pair on map.

        public List<List<String>> findDuplicate(String[] paths) {
            HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>();
            for(String s : paths){
                String[] splits = s.split(" ");
                for(int i = 1; i < splits.length; i++){
                    String[] splits2 = splits[i].split("(");
                    if(map.containsKey(splits2[0]) ){
                        ArrayList<String> temp = map.get(splits2[0]);
                        temp.add(splits[0] + "/" + splits2[1]);
                    }
                    else{
                        ArrayList<String> temp = new ArrayList<>();
                        temp.add(splits[0] + "/" + splits2[1]);
                        map.put(splits2[0],temp);
                    }
                }
            }
            List<List<String>> output = ArrayList<List<String>>();
            for(String key : map.keySet() ){
                if(map.get(key).size() > 1){
                    output.add(map.get(key) );
                }
            }
            return output;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.