49. Group anagrams

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

Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1: Input: strs = [“eat”,“tea”,“tan”,“ate”,“nat”,“bat”] Output: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]] Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = [“a”] Output: [[“a”]]

Constraints:

1 <= strs.length <= 104 	
0 <= strs[i].length <= 100 	
strs[i] consists of lowercase English letters.

  • code
class Solution {

    public String sortString(String word){
        char[] l = word.toCharArray();
        Arrays.sort(l);
        return String.valueOf(l);
        // return Stream.of(word.split("")).sorted().collect(Collectors.joining());
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List> m = new HashMap<>();
        for (String word: strs){
            String sorted = sortString(word);
            if (!m.containsKey(sorted)) m.put(sorted, new ArrayList());
            m.get(sorted).add(word);
        }
        return new ArrayList(m.values());
    }
}
  • code notice after sorted “eat”, it becomes [‘a’,‘e’,’t']
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dic_ana = {}
        for word in strs:
            sword = "".join(sorted(word))
            if sword not in dic_ana:
                dic_ana[sword] = [word]
            else:
                dic_ana[sword].append(word)
        
        return [v for v in dic_ana.values()]