给一字符串数组, 将 错位词(指相同字符不同排列的字符串) 分组
例1:
输入:
["eat","tea","tan","ate","nat","bat"]
输出:
[["ate","eat","tea"],
["bat"],
["nat","tan"]]
例2:
输入:
["eat","nowhere"]
输出:
[["eat"],
["nowhere"]]
所有的输入均为小写字母
其中Key存储分词排序的基词,即所有的错位词排序后都能得到这个词,Value存储该基词中包含数组中多少个错位词
class Solution {
public List> groupAnagrams(String[] strs) {
List> res = new ArrayList<>();
HashMap> map = new HashMap<>();
for(String str : strs){
char[] chars = str.toCharArray();
Arrays.sort(chars);
String tempString = new String(chars); //基词
if(!map.containsKey(tempString))
map.put(tempString, new ArrayList());
map.get(tempString).add(str);
}
for(List list : map.values())
res.add(new ArrayList(list));
return res;
}
}