我本来的思路是:通过26个字母构成长度为26的数组,这样统计每个单词都会生成对应的数组,数组相同的可以作为HashMap的键,把异位词作为值。但是后来发现数组不能作为键,索性用List直接存放每个词的字符并排序,代码如下,用时40ms:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<List<Character>, List<String>> sta = new HashMap<>();
for (String str : strs) {
List<Character> dict = new ArrayList<>();
for (int i = 0; i < str.length(); ++i)
dict.add(str.charAt(i));
Collections.sort(dict);
if (sta.containsKey(dict)) {
sta.get(dict).add(str);
}
else {
List<String> ls = new ArrayList<>();
ls.add(str);
sta.put(dict, ls);
}
}
List<List<String>> re = new ArrayList<List<String>>(sta.values());
return re;
}
}
后来发现最快的方法就是使用长度为26的数组作为键,只是聪明地对26位进行编码,有趣,代码中的静态变量 lenSize 应该是随意设定的,代码如下:
class Solution {
private static int lenSize = 7;
public List<List<String>> groupAnagrams(String[] strs) {
Map<Integer, List<String>> map = new HashMap();
List<List<String>> ans = new LinkedList();
for (int i = 0; i < strs.length; i++){
int hash = getHash(strs[i]);
List<String> lis = null;
if (map.containsKey(hash))
lis = map.get(hash);
else {
lis = new LinkedList();
ans.add(lis);
map.put(hash, lis);
}
lis.add(strs[i]);
}
return ans;
}
private int getHash(String str) {
int[] vis = new int[26];
for (int i = 0; i < str.length(); i++){
char ch = str.charAt(i);
vis[ch-'a']++;
}
int hash = 0;
for (int i = 0; i < vis.length; i++)
hash = hash * lenSize + vis[i];
return hash;
}
}
ArrayList 和 LinkedList 的大致区别,可进一步提高代码性能:
(1)ArrayList 是实现了基于动态数组的数据结构,LinkedList 基于链表的数据结构。
(2)对于随机访问 get 和 set ,ArrayList 优于 LinkedList,因为 LinkedList 要移动指针。
(3)对于新增和删除操作 add 和 remove,LinedList 比较占优势,因为 ArrayList 要移动数据。