Leetcode(49) Group Anagrams

Description

Given an array of strings, group anagrams together.

Example:

1
2
3
4
5
6
7
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.

解法

看到这个题,第一时间想到的就是采用哈希的方法,因为同类字符串的字母组成是相同的,那么如何哈希呢?思路是:先统计一个字符串里含各个字符的个数(第一次哈希,用一个长度为26的int数组统计对应字母的个数),再将这个int数组转化为字母字符串(这一步可以把字母组成相同的字符串转化为一样的字符串),再建立哈希表(第二次哈希),key为字母组成字符串(就是上一步生成的字符串),value为list,list中存组成相同的字符串。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
HashMap<String, List<String>> dict = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
int tmp[] = new int[26];
StringBuffer str = new StringBuffer();
for (int j = 0; j < strs[i].length(); j++) {
tmp[strs[i].charAt(j) - 'a'] += 1;
}
for (int j = 0; j < 26; j++) {
for (int k = 0; k < tmp[j]; k++) {
str.append((char) (j + 'a'));
}
}
if (dict.containsKey(str.toString())) {
dict.get(str.toString()).add(strs[i]);
} else {
List<String> newlist = new ArrayList<>();
newlist.add(strs[i]);
dict.put(str.toString(), newlist);
}
}
res.addAll(dict.values());
return res;
}
}