Given an array of strings, group anagrams together.
给定一个字符串数组,将同母异序词分组在一起
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
解:
因为组成字母相同只是顺序不同的话,那么对一个单词的所有字幕排序后得到的字符串如果相同,则表明他们是由相同字母组成的,顺序就不需要关心了。
所以思路就是先对每个字符串排序,排序后作为key为索引查找是否已存在分组,存在的加入分组,不存在就新建一个分组再加进去。
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> result = new HashMap<>();
for(String str:strs) {
char[] chars = str.toCharArray(); //所有的同字母异序词都由相同的字母构成
Arrays.sort(chars) ; //因为构成字母完全一样,所以排序后的字符串完全一样
String key = String.valueOf(chars);
result.compute(key, (k,v)->{
if(v == null) v = new ArrayList<>();
v.add(str);
return v;
});
}
return new ArrayList<>(result.values());
}