Problem Description:
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.
Analysis:
本题的题意是将队列中的所有使用相同个数字母的单词进行归类。本题的思路就是遍历整个序列,对每一个元素进行排序然后做hash值,判断其是否在之前存在过,如果存在过就插入到之前的队列中,否则就重新建立一个新的队列。
Code:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<List<String>>();
if(strs.length < 1) {
return res;
}
Map<String, List<String>> dict = new HashMap<>();
for(String ans : strs) {
char[] temp = ans.toCharArray();
Arrays.sort(temp);
String keys = new String(temp);
if(dict.containsKey(keys)) {
dict.get(keys).add(ans);
} else {
dict.put(keys, new ArrayList<>()
{{
add(ans);
}});
}
}
for(List<String> ll : dict.values()) {
res.add(ll);
}
return res;
}
}