One more way to make the key


  • 0
    S

    When I started with this question , like most of us, one thing I knew was I needed a hashmap to put anagrams together , the only question was what could be the key. This is what I came up with.

    There are smart solutions in the discussion forum. This is just another approach that might come handy and it is easy to remember

    public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, List<String>> hm = new HashMap<>();
            for(String s : strs){
                String key = getKey(s);
                if(!hm.containsKey(key)){
                    hm.put(key, new ArrayList<String>());
                }
                hm.get(key).add(s);
            }
        return new ArrayList<List<String>>(hm.values());
    }
    
    // makes key based on charater count eg "abaacb" = a3b2c1
    public String getKey(String s){
        int[] count = new int[26];
        for(char c : s.toCharArray()){
            int index = (int)(c - 'a');
            count[index] ++;
        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < count.length; i++){
            if(count[i] > 0){
                char c = (char)(i + 'a');
                sb.append(c);
                sb.append(count[i]);
            }
            
        }
        return sb.toString();
    }  
    

    }


Log in to reply
 

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