49. 字母异位词分组
利用每个字符的出现次数进行编码
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
排序
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());
}
}