题目
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
答案
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> list = new ArrayList<List<String>>();
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
for(int i = 0; i < strs.length; i++) {
char[] curr_chrs = strs[i].toCharArray();
Arrays.sort(curr_chrs);
String curr_str = String.valueOf(curr_chrs);
List<String> l = map.get(curr_str);
if(l == null) {
l = new ArrayList<String>();
list.add(l);
map.put(curr_str, l);
}
l.add(strs[i]);
}
return list;
}
}