Description
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.
Solution
HashMap, time O(n * logk), space O(n)
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> groups = new LinkedList<>();
if (strs == null) {
return groups;
}
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
String sorted = sort(s);
if (!map.containsKey(sorted)) {
map.put(sorted, new LinkedList<>());
}
map.get(sorted).add(s);
}
groups.addAll(map.values());
return groups;
}
public String sort(String s) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}