Accepted Java solution. O(n) time & space complexity. HashMap


  • 0
    O
    
        public List<List<String>> groupAnagrams(String[] strs) {
        	if (strs.length == 0) return new ArrayList<List<String>>();
        	List<String> list = null;
        	HashMap<String, List<String>> hash = new HashMap<String, List<String>>();
        	String mask;
        	char[] charList = null;
        	for(String str: strs) {
        		list = null;
        		charList = str.toCharArray();
        		Arrays.sort(charList);
        		mask = new String(charList);
        		if (hash.containsKey(mask)) {
        			list = hash.get(mask);
        			list.add(str);
        			hash.put(mask, list);
        		} else {
        			list = new ArrayList<String>();
        			list.add(str);
        			hash.put(mask, list);
        		}
        	}
        	List<List<String>> result = new ArrayList<List<String>>();
        	for(List<String> value: hash.values()) {
        		result.add(value);
        	}
        	return result;
        }
    

Log in to reply
 

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