Given an array of strings, group anagrams together.
給定一個(gè)字符串?dāng)?shù)組,將同母異序詞分組在一起
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.
解:
因?yàn)榻M成字母相同只是順序不同的話,那么對一個(gè)單詞的所有字幕排序后得到的字符串如果相同,則表明他們是由相同字母組成的,順序就不需要關(guān)心了。
所以思路就是先對每個(gè)字符串排序,排序后作為key為索引查找是否已存在分組,存在的加入分組,不存在就新建一個(gè)分組再加進(jìn)去。
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> result = new HashMap<>();
for(String str:strs) {
char[] chars = str.toCharArray(); //所有的同字母異序詞都由相同的字母構(gòu)成
Arrays.sort(chars) ; //因?yàn)闃?gòu)成字母完全一樣,所以排序后的字符串完全一樣
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());
}