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.
[code lang="java"]
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
}
}
[code]
Idea – 1
Sorted version of a group of anagrams is unique, so we shall use a hashmap to group the anagrams where key will be the sorted version. Since all strings consist of lowercase letters only, we use counting sort to perform sorting in
[code lang="java"]
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ans = new ArrayList<>();
if(strs==null || strs.length==0)
{
return ans;
}
HashMap<String, List<String>> map = new HashMap<>();
for(String w : strs)
{
// 26 unique chars
char[] counts = new char[26];
for(int i = 0; i < w.length(); ++i)
{
++counts[ w.charAt(i)-'a' ];
}
String sorted = new String(counts);
List<String> group = map.getOrDefault(sorted, new ArrayList<>());
group.add(w);
map.put(sorted, group);
}
for(String key : map.keySet())
{
ans.add(map.get(key));
}
return ans;
}
}
[code]
Runtime: 9 ms, faster than 89.34% of Java online submissions for Group Anagrams.Memory Usage: 40.7 MB, less than 93.53% of Java online submissions for Group Anagrams.