congr / world

2 stars 1 forks source link

49. Group Anagrams #378

Closed congr closed 6 years ago

congr commented 6 years ago

https://leetcode.com/problems/group-anagrams/description/ image

congr commented 6 years ago

Medium, but it's very simple

congr commented 6 years ago
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, ArrayList<String>> map = new HashMap();

        for(int i=0; i<strs.length; i++) {
            char[] ch = strs[i].toCharArray();
            Arrays.sort(ch);
            String str = String.valueOf(ch); // String.valueOf([a,b,c]) -> "abc"
            ArrayList<String> al = map.getOrDefault(str, new ArrayList());
            al.add(strs[i]);
            map.put(str, al);
        }

        return new ArrayList(map.values());
    }
}
congr commented 5 years ago
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap();

        for(String s: strs) {
            char[] ch = s.toCharArray();
            Arrays.sort(ch);
            String str = String.valueOf(ch); // String.valueOf([a,b,c]) -> "abc"
            List<String> al = map.getOrDefault(str, new ArrayList());
            al.add(strs[i]);
            map.put(str, al);
        }

        return new ArrayList(map.values()); // [["tan", "nat"], ["bat", "tab"]]
    }
}