[JAVA] Use hashmap and use content as key / T : O(N), S : O(N)


  • 0
    J
    public class Solution {
        public List<List<String>> findDuplicate(String[] paths) {
            List<List<String>> result = new ArrayList<List<String>>();
            HashMap<String, List<String>> map = new HashMap<String, List<String>>();
            for(int i = 0; i < paths.length; i++){
                String[] pathInfo = paths[i].split(" ");
                String directory = pathInfo[0];
                for(int j = 1 ; j < pathInfo.length; j++){
                    String key = pathInfo[j].split("\\(")[1].split("\\)")[0];
                    String value = directory + '/' + pathInfo[j].split("\\(")[0];
                    
                    if(!map.containsKey(key)){
                       map.put(key, new ArrayList<String>()); 
                    }
                    map.get(key).add(value);
                }
            }
            
            for(String key : map.keySet()){
                if(map.get(key).size() > 1)
                    result.add(map.get(key));
            }
            
            return result;
        }
    }
    

Log in to reply
 

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