-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
90 lines (79 loc) · 1.87 KB
/
Copy pathTrie.java
File metadata and controls
90 lines (79 loc) · 1.87 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package templates;
class Node {
char ch;
boolean output;
Node[] next;
int count;
public Node(char data) {
this.ch = data;
output = false;
next = new Node[26];
count = 0;
}
}
public class Trie {
Node root;
int wordCount;
public Trie() {
root = new Node('\0');
wordCount = 0;
}
private void add( Node root,String word,int i) {
if (i==word.length()) {
root.output = true;
return;
}
char c=word.charAt(i);
int ind =c-'a' ;
Node child = root.next[ind];
if (child == null) {
child = new Node(c);
root.next[ind]=child;
root.count++;
}
add(child,word,i+1);
}
public void add(String word) {
add(root,word,0);
wordCount++;
}
private boolean search(Node root,String word,int i) {
if (i==word.length()) {
return root.output;
}
char c=word.charAt(i);
int ind =c-'a' ;
Node child = root.next[ind];
if (child == null) {
return false;
}
return search(child,word,i+1);
}
public boolean search(String word) {
return search(root,word,0);
}
private void remove(Node root,String word,int i) {
if (i==word.length()) {
root.output = false;
return;
}
char c=word.charAt(i);
int ind =c-'a' ;
Node child = root.next[ind];
if (child == null) {
return;
}
remove(child,word,i+1);
if (!child.output && child.count == 0) {
root.next[ind] = null;
child = null;
root.count--;
}
}
public void remove(String word) {
if (search(word)) {
remove( root,word,0);
wordCount--;
}
}
}