Solve the problem with out sorting


  • 0
    W

    The time is O(m+k), k is the number of letters. It should faster than sorting.

    public List<List<String>> groupAnagrams(String[] strs) {
            if (strs.length ==0) {
                return new ArrayList<>();
            }
            Map<String,List<String>> group = new HashMap<>();
            for (int i=0;i<strs.length;i++) {
                String sum = this.getAsiiSum(strs[i]);
                List<String> listStr = group.get(sum);
                if(listStr == null) {
                    listStr = new ArrayList<>();
                    listStr.add(strs[i]);
                    group.put(sum,listStr);
                }
                else {
                    listStr.add(strs[i]);
                }
            }
            List<List<String>> outPut = new ArrayList<>();
            for(String key : group.keySet()) {
                outPut.add(group.get(key));
            }
            return outPut;
        }
    
        private String getAsiiSum(String str) {
            char[] com = new char[26];
            int result = 0;
            for (int i = 0;i<str.length();i++) {
                char c = str.charAt(i);
                com[c-'a'] ++;
            }
            return new String(com) + str.length();
        }

  • 0
    W

    in this case the last str.lengtt() is useless, we can remove it


Log in to reply
 

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