49. Group Anagrams

iven 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.
 1 class Solution {
 2     public String change(String a) {
 3         char[] temp = a.toCharArray();
 4         Arrays.sort(temp);
 5         String s = String.valueOf(temp);
 6         return s;
 7     }
 8     public List<List<String>> groupAnagrams(String[] strs) {
 9         int k = 0;
10         List<List<String>> ans = new ArrayList<>();
11         int n = strs.length;
12         Map<String, List<String>>map = new HashMap<>();
13         for (int i = 0; i < n; ++i) {
14             String temp = change(strs[i]);
15             if (!map.containsKey(temp)){
16                 List<String> t = new ArrayList<>();
17                 ans.add(t);
18                 map.put(temp, t);
19                 map.get(temp).add(strs[i]);
20             } else {
21                 map.get(temp).add(strs[i]);
22             }
23         }
24         
25         return ans;
26     }
27 }
原文地址:https://www.cnblogs.com/hyxsolitude/p/12322136.html