[LeetCode] Group Anagram

linspiration發表於2019-01-19

Problem

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

All inputs will be in lowercase.
The order of your output does not matter.

Solution

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        if (strs == null || strs.length == 0) return res;
        Map<String, List<String>> map = new HashMap<>();                        //use HashMap to store grouped anagrams 
        for (String str: strs) {
            char[] charArray = str.toCharArray();
            Arrays.sort(charArray);                                             //sort each string to match existing key
            String anagram = String.valueOf(charArray);
            if (!map.containsKey(anagram)) {                                    //if not existed, create a list
                map.put(anagram, new ArrayList<>());
            }
            map.get(anagram).add(str);                                          //put the original string into its anagram group
        }
        for (Map.Entry<String, List<String>> entry: map.entrySet()) {           //use Map.Entry from map.entrySet() to iterate
            List<String> anagrams = entry.getValue();
            Collections.sort(anagrams);                                         //sort it in lexicographic order
            res.add(anagrams);
        }
        return res;
    }
}

相關文章