Java Anagrams Solution with explanation.


  • 0
    V

    The idea is that, we sort each strings, and then compare if they are equal. Use HashMap<String,
    List<String>> map to record the sorted string and its corresponding list: if the sorted string has already exist in the map, just add this string into the list; if the sorted string is not exist in the map, create a new list to hold this string and add this relationship into hashmap.

    public class Solution {

    public List<List<String>> groupAnagrams(String[] strs) {
    
        List<List<String>> ret = new ArrayList<List<String>>();
        if(strs == null || strs.length == 0){
            return ret;
        }
        
        HashMap<String, List<String>> map = new HashMap<String, List<String>>();
        
        for(int i = 0; i < strs.length; i++){
            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);
            String s = new String(chars);
            
            if(!map.containsKey(s)){
                List<String> list = new ArrayList<String>();
                list.add(strs[i]);
                map.put(s, list);
                ret.add(list);
            }else{
                List<String> ls = map.get(s);
                ls.add(strs[i]);
                Collections.sort(ls);
            }
        }
        
        return ret;
    }
    

    }


Log in to reply
 

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