Given 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.
将每一个string映射到一个26位的数组上,映射成一个key,然后将key放入map中,value就是拥有相同key的list。 最后遍历map,将list取出,放入result中即可。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
// 将字符串映射为key
String s = strs[i];
int[] tmp = new int[26];
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
tmp[c - 'a']++;
}
StringBuilder sb = new StringBuilder();
for (int x = 0; x < 26; x++) {
sb.append(tmp[x]);
}
String key = sb.toString();
// 把字符串装入map中的key对应的list中
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(s);
}
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
result.add(entry.getValue());
}
return result;
}
}