利用每个字符的出现次数进行编码
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
for(String str : strs){
String code = encode(str);
map.putIfAbsent(code, new ArrayList<>());
map.get(code).add(str);
}
return new ArrayList<>(map.values());
}
String encode(String str){
char[] cnt = new char[26];
for(char c : str.toCharArray()){
cnt[c - 'a']++;
}
return new String(cnt);
}
}
排序
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
for(String str : strs){
char[] ch = str.toCharArray();
Arrays.sort(ch);
String sorted = new String(ch);
map.putIfAbsent(sorted, new ArrayList<>());
map.get(sorted).add(str);
}
return new ArrayList<>(map.values());
}
}