2.字母异位词分组
大约 2 分钟
2.字母异位词分组
参考链接
个人尝试❌
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// 参数校验
if (strs == null || strs.length == 0) return new ArrayList<List<String>>();
// key:char-ASCII,value:res的index
Map<Integer, Integer> map = new HashMap<>();
// 返回参数
List<List<String>> res = new ArrayList<>();
// String[] 转 char[][]
char[][] cs = new char[strs.length][strs[0].length()];
for (int i = 0; i < strs.length; i++) {
cs[i] = strs[i].toCharArray();
}
// 根据key判断map中是否存在,存在放入List
// 不存在,新建List
for (int i = 0; i < cs.length; i++) {
int key = 0;
for (int j = 0; j < cs[i].length; j++) key += cs[i][j];
if (map.containsKey(key)) {
// 根据key获取res中对应的List
List<String> list = res.get(map.get(key));
list.add(String.valueOf(cs[i]));
} else {
// 新建List
List<String> list = new ArrayList<>();
list.add(String.valueOf(cs[i]));
res.add(list);
map.put(key, res.size() - 1);
}
}
return res;
}
}
代码存在问题;
当遇到 ["duh","ill"]
即 字符ASCII相加 可能出现不是 同一组字母异位词 但是 ASCII码 相同的情况;
应当修改为:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// 参数校验
if (strs == null || strs.length == 0) return new ArrayList<List<String>>();
// key:String-hashCode,value:res的index
Map<String, Integer> map = new HashMap<>();
// 返回参数
List<List<String>> res = new ArrayList<>();
// String[] 转 char[][]
char[][] cs = new char[strs.length][strs[0].length()];
for (int i = 0; i < strs.length; i++) {
cs[i] = strs[i].toCharArray();
}
// 根据key判断map中是否存在,存在放入List
// 不存在,新建List
for (int i = 0; i < cs.length; i++) {
Arrays.sort(cs[i]);
String key = String.valueOf(cs[i]);
if (map.containsKey(key)) {
// 根据key获取res中对应的List
List<String> list = res.get(map.get(key));
list.add(strs[i]);
} else {
// 新建List
List<String> list = new ArrayList<>();
list.add(strs[i]);
res.add(list);
map.put(key, res.size() - 1);
}
}
return res;
}
}
优秀题解
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String str : strs) {
char[] array = str.toCharArray();
Arrays.sort(array);
String key = new String(array);
List<String> list = map.getOrDefault(key, new ArrayList<String>());
list.add(str);
map.put(key, list);
}
return new ArrayList<List<String>>(map.values());
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/group-anagrams/solutions/520469/zi-mu-yi-wei-ci-fen-zu-by-leetcode-solut-gyoc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。