Java - O(n) solution Content->paths Hashmap


  • 0
    public class Solution {
        public List<List<String>> findDuplicate(String[] paths) {
            Map<String, List<String>> contentToFilePathsMap = new HashMap<>();
            for(String path : paths) {
                String[] components = path.split("\\s+");
                String dir = components[0];
                for(int i = 1; i < components.length; i++) {
                    int indexFirstPar = components[i].indexOf("(");
                    String fileName = components[i].substring(0, indexFirstPar);
                    String contents = components[i].substring(indexFirstPar + 1, components[i].length() - 1);
                    List<String> filePaths = contentToFilePathsMap.get(contents);
                    if(filePaths == null) {
                        filePaths = new ArrayList<>();
                        contentToFilePathsMap.put(contents, filePaths);
                    }
                    filePaths.add(dir + '/' + fileName);
                }
            }
            
            
            List<List<String>> result = new ArrayList<>();
            for(String content : contentToFilePathsMap.keySet()) {
                List<String> filePaths = contentToFilePathsMap.get(content);
                if(filePaths.size() >= 2) {
                    result.add(filePaths);    
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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