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.
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
if (strs == null || strs.length == 0) return res;
Map<String, Integer> m = new HashMap<>();
for (String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sortedStr = new String(chars);
if (m.containsKey(sortedStr)) {
int index = m.get(sortedStr);
res.get(index).add(str);
} else {
m.put(sortedStr, res.size());
List<String> group = new ArrayList<>();
group.add(str);
res.add(group);
}
}
return res;
}
beats 97.78% of javasubmissions.