LeetCode 49. 字母异位词分组
程序员文章站
2022-07-12 12:49:27
...
题目地址:https://leetcode-cn.com/problems/group-anagrams/submissions/
思路:将每个字符串排序一下,key=排序后的字符, value=原始的字符,放在map中即可
AC代码:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
String key = sort(strs[i]);
List<String> list = map.get(key);
if (list == null) {
list = new ArrayList<>();
list.add(strs[i]);
map.put(key, list);
} else {
list.add(strs[i]);
}
}
List<List<String>> resultList = new ArrayList<>();
for (List<String> list : map.values()) {
resultList.add(list);
}
return resultList;
}
private String sort(String str) {
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
return new String(charArray);
}
}
上一篇: rabbitmq安装
下一篇: leetcode 49. 字母异位词分组