Clean and understandable java solution


  • 7
    W
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, List<String>> words = new HashMap<String, List<String>>();
        for(String str : strs){
            String key = getKey(str);
            if(words.containsKey(key)){
                words.get(key).add(str);
            } else {
                List<String> l = new ArrayList<String>();
                l.add(str);
                words.put(key, l);
            }
        }
        List<List<String>> results = new ArrayList<List<String>>();
        for(String k : words.keySet()){
            List<String> r = words.get(k);
            Collections.sort(r);
            results.add(r);
        }
        return results;
    }
    
    public String getKey(String str){
        char[] c = str.toCharArray();
        Arrays.sort(c);
        return String.valueOf(c);
    }

Log in to reply
 

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