Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
Hashmap解题,key 的选择是关键,这里的 key 采用 Arrays.sort(string.toCharArray()) 的思路。代码如下:public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> hs = new HashMap<String, List<String>>();
for (String str: strs) {
char[] chs = str.toCharArray();
Arrays.sort(chs);
String tempStr = new String(chs);
if (!hs.containsKey(tempStr)) {
hs.put(tempStr, new ArrayList<String>());
}
hs.get(tempStr).add(str);
}
return new ArrayList<List<String>>(hs.values());
}
}
另一种方案,用素数的乘积来作为key,但是如果溢出就失败了。代码如下:
public static List<List<String>> groupAnagrams(String[] strs) {
int[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103};//最多10609个z
List<List<String>> res = new ArrayList<>();
HashMap<Integer, Integer> map = new HashMap<>();
for (String s : strs) {
int key = 1;
for (char c : s.toCharArray()) {
key *= prime[c - 'a'];
}
List<String> t;
if (map.containsKey(key)) {
t = res.get(map.get(key));
} else {
t = new ArrayList<>();
res.add(t);
map.put(key, res.size() - 1);
}
t.add(s);
}
return res;
}
}