49 Submission Details
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
if (strs.length == 0) {
return result;
}
Map<String, List<String>> ht = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] a = strs[i].toCharArray();
Arrays.sort(a);
String temp = new String(a);
if (ht.containsKey(temp)) {
ht.get(temp).add(strs[i]);
} else {
List<String> l = new ArrayList<>();
l.add(strs[i]);
ht.put(temp, l);
}
}
for (List<String> l : ht.values()) {
result.add(l);
}
return result;
}
}
浙公网安备 33010602011771号