Group Anagrams(Don's use array as key of map)

https://leetcode.com/problems/group-anagrams/\#/description

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        List<List<String>> res = new ArrayList<>();
        for(int i = 0; i < strs.length; i++){
            char[] str = strs[i].toCharArray();
            Arrays.sort(str);
            String key = String.valueOf(str);
            if(!map.containsKey(key)){
                map.put(key, new ArrayList<String>());
            }
            map.get(key).add(strs[i]);
        }

        for(Map.Entry<String, List<String>> e : map.entrySet()){
            res.add(e.getValue());
        }

        return res;
    }
}

Wrong answer, you cannot use an array as key of HashMap, as map use equals to check if two keys are the same. And array1.equals(array2) only if array1 and array2 are the same object.(https://stackoverflow.com/questions/16839182/can-a-java-array-be-used-as-a-hashmap-key\)

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<char[], List<String>> map = new HashMap<>();
        List<List<String>> res = new ArrayList<>();
        for(int i = 0; i < strs.length; i++){
            char[] str = strs[i].toCharArray();
            Arrays.sort(str);
            if(map.containsKey(str)){
                map.get(str).add(strs[i]);
            }else{
                map.put(str, new ArrayList<>());
                map.get(str).add(strs[i]);
            }
        }

        for(Map.Entry<char[], List<String>> e : map.entrySet()){
            res.add(e.getValue());
        }

        return res;
    }
}

results matching ""

    No results matching ""