O(n) solution, with no sort no prime trick


  • 0
    M
    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            Map<Integer, List<String>> map = new HashMap<>(strs.length);
            for(String str : strs){
                int hashcode = getHashCode(str);
                List<String> anagram = map.get(hashcode);
                if(anagram==null){
                    anagram = new ArrayList<>();
                    map.put(hashcode, anagram);
                }
                anagram.add(str);
            }
            return new ArrayList<>(map.values());
        }
        
        private int getHashCode(String str){
            final int N = str.length();
            int[] counter = new int[26];
            for(int i=0; i<N; i++){
                counter[str.charAt(i)-'a']++;
            }
            return Arrays.hashCode(counter);
        }
    }
    

Log in to reply
 

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