-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.java
70 lines (56 loc) · 1.46 KB
/
Trie.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
63
64
65
66
67
68
69
70
package database;
import java.util.*;
class TrieNode {
TrieNode[] arr;
boolean isEnd;
public TrieNode() {
this.arr = new TrieNode[26];
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode pNode = root;
for(int i=0; i<word.length(); i++){
char c = word.charAt(i);
int index = c-'a';
if(index > 0)
if(pNode.arr[index]==null){
TrieNode temp = new TrieNode();
pNode.arr[index]=temp;
pNode = temp;
}else{
pNode=pNode.arr[index];
}
}
pNode.isEnd=true;
}
public boolean search(String word) {
TrieNode pSearchedNode = searchNode(word);
if(pSearchedNode == null){
return false;
}else{
if(pSearchedNode.isEnd)
return true;
}
return false;
}
public TrieNode searchNode(String s){
TrieNode p = root;
for(int i=0; i<s.length(); i++){
char c= s.charAt(i);
int index = c-'a';
if(p.arr[index]!=null){
p = p.arr[index];
}else{
return null;
}
}
if(p==root)
return null;
return p;
}
}