-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplementTrie2
58 lines (52 loc) · 1.36 KB
/
ImplementTrie2
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
53
54
55
56
57
58
public class Trie {
Trie[] t;
int countWords;
int countWordsStartingWith;
public Trie() {
t = new Trie[26];
countWords = 0;
countWordsStartingWith=0;
}
public void insert(String word) {
Trie root = this;
for(char c : word.toCharArray()){
if(root.t[c-'a']==null){
root.t[c-'a'] = new Trie();
}
root = root.t[c-'a'];
root.countWordsStartingWith++;
}
root.countWords++;
}
public int countWordsEqualTo(String word) {
Trie root = this;
for(char c : word.toCharArray()){
if(root.t[c-'a']==null){
return 0;
}
root = root.t[c-'a'];
}
return root.countWords;
}
public int countWordsStartingWith(String word) {
Trie root = this;
for(char c : word.toCharArray()){
if(root.t[c-'a']==null){
return 0;
}
root = root.t[c-'a'];
}
return root.countWordsStartingWith;
}
public void erase(String word) {
Trie root = this;
for(char c : word.toCharArray()){
if(root.t[c-'a']==null){
break;
}
root = root.t[c-'a'];
root.countWordsStartingWith--;
}
root.countWords--;
}
}