-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
62 lines (55 loc) · 1.44 KB
/
Solution.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
53
54
55
56
57
58
59
60
61
62
class Trie {
private Trie[] children = new Trie[26];
private int v;
private int pv;
public Trie() {
}
public void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
++node.pv;
}
++node.v;
}
public int countWordsEqualTo(String word) {
Trie node = search(word);
return node == null ? 0 : node.v;
}
public int countWordsStartingWith(String prefix) {
Trie node = search(prefix);
return node == null ? 0 : node.pv;
}
public void erase(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
node = node.children[c];
--node.pv;
}
--node.v;
}
private Trie search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return null;
}
node = node.children[c];
}
return node;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* int param_2 = obj.countWordsEqualTo(word);
* int param_3 = obj.countWordsStartingWith(prefix);
* obj.erase(word);
*/