/*
非最优解法,有额外空间
*/
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<String> path = new ArrayList<String>();
List<List<String>> rst = new ArrayList<>();
if (strs == null || strs.length == 0) {
return rst;
}
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for (String s : strs) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
String key = new String(arr);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(s);
}
for (String s : map.keySet()) {
path = new ArrayList<String>();
path = map.get(s);
Collections.sort(path);
rst.add(path);
}
return rst;
}
}
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<String> path = new ArrayList<String>();
List<List<String>> result = new ArrayList(path);
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
for (String str : strs) {
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i) - 'a']++;
}
int hash = getHash(count);
if (!map.containsKey(hash)) {
map.put(hash, new ArrayList<String>());
}
map.get(hash).add(str);
}
for (ArrayList<String> tmp : map.values()) {
result.add(tmp);
}
return result;
}
private int getHash(int[] count) {
int hash = 0;
int a = 378551;
int b = 63689;
for (int num : count) {
hash = a * hash + num;
a = a * b;
}
return hash;
}
}