-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathgroup_anagrams.java
52 lines (43 loc) · 1.13 KB
/
group_anagrams.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
46
47
48
49
50
51
52
class TrieNode {
List<String> data;
TrieNode children[];
boolean isEnd;
TrieNode(){
data = new ArrayList<>();
children = new TrieNode[26];
isEnd = false;
}
}
class Solution {
static TrieNode root;
List<List<String>> ans;
public List<List<String>> groupAnagrams(String[] strs) {
ans = new ArrayList<>();
root = new TrieNode();
for(String word: strs){
build(word);
}
dfs(root);
return ans;
}
public void build(String s){
TrieNode temp = root;
char[] word = s.toCharArray();
Arrays.sort(word);
for(char c: word){
TrieNode child = temp.children[c-'a'];
if(child == null) temp.children[c-'a'] = new TrieNode();
temp = temp.children[c-'a'];
}
temp.isEnd = true;
temp.data.add(s);
}
public void dfs(TrieNode rt){
if(rt.isEnd){
ans.add(rt.data);
}
for(int i = 0; i < 26; i++){
if(rt.children[i] != null) dfs(rt.children[i]);
}
}
}