Group Anagrams
Description
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.
Solution
1. HashMap and Sorted Array
-
将每一个string转换成字符数组后,把这个数组按字母顺序排序
-
新建一个HashMap,key为排序后的字符数组,value为对应的string组成的List
-
注意: HashMap中的key不可以用字符数组char[],因为数组的hashCode实际上只是该数组的reference。此时,应将char[]再次转换为string,把这个string当做HashMap的key。String is immutable.
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> hashMap = new HashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if (!hashMap.containsKey(key)) hashMap.put(key, new ArrayList());
hashMap.get(key).add(s);
}
return new ArrayList(hashMap.values());
}
}
Time complexity: O(NlgK)
, K
是字符串的长度, N
是数组中字符串的个数。
2. Count Sort
-
由于所有字符串中只包含26个小写字母,因此在
HashMap
中的key
是一个长度为26的array
,array
的index
对应为该字母在string
中出现的次数。 -
HashMap
中的value
为对应的字符串组成的List
。 -
注意: 不可把数组作为HashMap中的key,此时应当将这个数组转换成一个独一无二的数据结构,例如,不相同的数组应该给出不同的key值。
- 将
int
数组转换成字符串,每一个数字之间用“#”隔开 - 直接计算
int
数组的hashCode
,使用Arrays.deepHashCode()
- 将
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<Integer, List<String>> hashMap = new HashMap<>();
for (String s : strs) {
Integer[] alpha = new Integer[26];
Arrays.fill(alpha, 0);
for (int i = 0; i < s.length(); i++)
alpha[s.charAt(i) - 'a']++;
int key = Arrays.deepHashCode(alpha);
if (!hashMap.containsKey(key)) hashMap.put(key, new ArrayList());
hashMap.get(key).add(s);
}
return new ArrayList(hashMap.values());
}
}
- Time complexity:
O(KN)
,K
is26
, which is the size of alphabet. This is a linear solution. - Space complexity:
O(KN)
3. Unique prime number
- Use unique prime number for each character in the alphabet. When come to each character, maintain a product, and time the prime number to the product. A string will have a unique integer.
- This is the fastest method.