-
Notifications
You must be signed in to change notification settings - Fork 0
/
groupAnagram.java
45 lines (34 loc) · 885 Bytes
/
groupAnagram.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
49. Group Anagrams
Medium
1161
79
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.
*/
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(String w : strs){
String key = hash(w); // find hash key
if(!map.containsKey(key)) map.put(key, new LinkedList<>());
map.get(key).add(w);
}
return new ArrayList<>(map.values());
}
String hash(String s){
int[] a = new int[26];
for(char c : s.toCharArray()) a[c-'a']++; // occurance
return Arrays.toString(a);
}
}