Given an array of strings, group anagrams together.
Example
NOTE
- Knowledge about map has been forgotten, should be reviewed.
Solution 1
Consideration
- use a map to store the patterns
- for each string, sort it first, then check if it is in the map. If yes, append to the list. Otherwise, put the new key to the map and append the string to the list.
Time Complexity: O(NKlogK), where N is the length of strs, and K is the maximum length of a string in strs. The outer loop has complexity O(N) as we iterate through each string. Then, we sort each string in O(KlogK) time.
Space Complexity: O(NK), the total information content stored in ans.
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0)
return new ArrayList();
Map<String,List> map = new HashMap();
for(String s:strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String new_str = String.valueOf(chars);
if(!map.containsKey(new_str)) {
map.put(new_str, new ArrayList());
}
map.get(new_str).add(s);
}
return new ArrayList(map.values());
}
}
Solution 2
Consideration
- Use a array to store the count of each characters
- Use a map to store the count pattern
- Convert the count to string, and check if the map contains the pattern key.
Time Complexity: O(NK), where N is the length of strs, and K is the maximum length of a string in strs.
Space Complexity: O(NK)
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0)
return new ArrayList();
Map<String,List> map = new HashMap();
int[] count = new int[26];
for(String s:strs) {
Arrays.fill(count, 0);
char[] chars = s.toCharArray();
for(char c: chars)
++count[c-'a'];
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < 26; i++) {
sb.append('#');
sb.append(count[i]);
}
String new_str = sb.toString();
if(!map.containsKey(new_str)) {
map.put(new_str, new ArrayList());
}
map.get(new_str).add(s);
}
return new ArrayList(map.values());
}
}
Solution 3
Consideration
- Use 26 primes to represent 26 alphabets. As for primes, different combinations the multiplications will be different.
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0)
return new ArrayList();
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103};
Map<Integer, List<String>> map = new HashMap<>();
for(String str:strs) {
int k = 1;
for(char ch:str.toCharArray()) {
k *= primes[ch-'a'];
}
if(!map.containsKey(k)) {
map.put(k, new ArrayList<>());
}
map.get(k).add(str);
}
return new ArrayList<List<String>>(map.values());
}
}
References