JAVA sort and HashMap approach but using <String, Integer>


  • 0
    4
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        
        if (strs == null || strs.length == 0) {
            return res;
        } 
        
        Map<String, Integer> m = new HashMap<>();
        
        for (String str : strs) {
            String sortedStr = sortString(str);
            
            if (m.containsKey(sortedStr)) {
                int index = m.get(sortedStr);
                res.get(index).add(str);
            } else {
                m.put(sortedStr, res.size());
                List<String> group = new ArrayList<>();
                group.add(str);
                res.add(group);
            }
        }
        
        return res;
    }
    
    private String sortString (String str) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
    

    HashMap records where the certain anagram group is at in the result list. This eliminates the work to go through the values of HashMap if we used <String, List<string>> instead


Log in to reply
 

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