Question:

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.

Thinking:

  • 这种情况肯定会想到hashmap,但是应该如何设计map?
  • 我们知道被归为一类的字符串在排序后是相同的,这点对于所有的找出相同字母都适用。
    • 这种情况下我们将排序后的字符串作为键,如果相同就是存入该键对应的集合中。
    • 如果不相同新建。
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new ArrayList<>();
        if(strs == null || strs.length == 0) return result;
        Map<String, List<String>> m = new HashMap<>();
        for(String str : strs){
            char[] strArr = str.toCharArray();
            Arrays.sort(strArr);
            String cur = new String(strArr);
            if(!m.containsKey(cur)){
                List<String> temp = new ArrayList<String>();
                temp.add(str);
                m.put(cur, temp);
            }else{
                m.get(cur).add(str);
            }
        }
        result.addAll(m.values());
        return result;
    }
}

二刷

还是想到要用哈希表,但是问题仍然是如何设置键和值,键是sort过后的字符串,值是链表。

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new LinkedList<>();
        if(strs == null || strs.length == 0) return result;
        Map<String, List<String>> map = new HashMap<>();
        for(int i = 0; i < strs.length; i++){
            char[] t = strs[i].toCharArray();
            Arrays.sort(t);
            String temp = new String(t);
            if(!map.containsKey(temp))
                map.put(temp, new LinkedList<String>());
            map.get(temp).add(strs[i]);
        }
        result.addAll(map.values());
        return result;
    }
}

Amazon session

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for(String s : strs){
            String copy = new String(s);
            char[] arr = copy.toCharArray();
            Arrays.sort(arr);
            String reorder = new String(arr);
            List<String> list = map.getOrDefault(reorder, new ArrayList<>());
            list.add(s);
            map.put(reorder, list);
        }
        List<List<String>> result = new ArrayList<>();
        for(List<String> value : map.values()){
            result.add(value);
        }
        return result;
    }
}