这里使用HashMap
Java
package _49;
import java.util.*;
public class Problem_49_GroupAnagrams {
public List<List<String>> groupAngrams(String [] strs){
Map<String,List<String>> map = new HashMap<>();
// int [] arr = new int[]{};
for(String s : strs){
char[] chars = s.toCharArray();
Arrays.sort(chars);//排序之后的字母异位词都是一样,因此可以作为map的key
String key = String.valueOf(chars);
if(!map.containsKey(key)) map.put(key,new ArrayList<>());
map.get(key).add(s);
}
return new ArrayList<>(map.values());//
}
}
public List<List<String>> groupAnagrams1(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
int[] count = new int[26];
for (char c : chars) count[c - 'a']++;
String key = Arrays.toString(count);//int: 32位有符号整数,范围是-2^31到2^31-1。
if (!map.containsKey(key)) map.put(key, new ArrayList<>());
map.get(key).add(s);
}
return new ArrayList<>(map.values());
}
C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> map;
for (string& str : strs) {
vector<int> count(26);
for (char c : str) count[c - 'a']++;
string key = "";
for (int i = 0; i < 26; i++) key += count[i];
map[key].emplace_back(str);
}
vector<vector<string>> ans;
for (auto it = map.begin(); it != map.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
vector<vector<string>> groupAnagrams1(vector<string>& strs) {
unordered_map<string, vector<string>> map;
for (string& str : strs) {
string key = str;
sort(key.begin(), key.end());
map[key].emplace_back(str);
}
vector<vector<string>> ans;
for (auto it = map.begin(); it != map.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
};