LeetCode传送门:字母异位词分组
题目描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
思路
- 遍历字符串数组,每个元素排序后,作为map的key。
- 不断添加所有元素,最后返回,这样同一个key对应的多个字符串就被连接到了同一个链表里。
- 字符数组排序使用Arrays.sort()。
Java代码实现
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char []c = strs[i].toCharArray();
Arrays.sort(c);
String key = String.valueOf(c);
if (map.containsKey(key)){
map.get(key).add(strs[i]);
}else {
List<String> temp = new ArrayList<>();
temp.add(strs[i]);
map.put(key,temp);
}
}
return new ArrayList<List<String>>(map.values());
}
}
如有错误之处请留言指正。