题目描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
- 示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[[“ate”,“eat”,“tea”], [“nat”,“tan”], [“bat”]]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
维护一个HashMap,key为经过字符排序后的字符串,value为key的字母异位词列表(包含key本身)
代码详解
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> hm = new HashMap<>();
for(String s : strs) {
char[] words = s.toCharArray();
Arrays.sort(words); // 先排序,转换成String后再作为key
String newS = new String(words);
// 维护HashMap的过程
if(hm.containsKey(newS)) {
hm.get(newS).add(s);
} else {
List<String> tempList = new ArrayList<>();
tempList.add(s);
hm.put(newS, tempList);
}
}
return new ArrayList<>(hm.values());
}
}
注意点
- 为什么需要将String先转换成char[]、再排序、再转换回String呢?
String的containsKey是调用equals(),而char[]的containsKey比较的是地址(此说法如有误请评论指出)