-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.java
68 lines (52 loc) · 1.43 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
public class Trie {
static class Node{
Node[] children;
boolean eow;
public Node(){
children=new Node[26];
for(int i=0;i<26;i++){
children[i]=null;
}
eow=false;
}
}
static Node root=new Node();
public static void insert(String word){
Node curr=root;
for(int i=0;i<word.length();i++){
int idx=word.charAt(i)-'a';
if(curr.children[idx]==null){
//add new node
curr.children[idx]=new Node();
}
if(i==word.length()-1){
curr.children[idx].eow=true;
}
curr=curr.children[idx];
}
}
public static boolean search
(String key){
Node curr=root;
for(int i=0;i<key.length();i++){
int idx=key.charAt(i)-'a';
Node node=curr.children[idx];
if(node==null){
return false;
}
if(i==key.length()-1 && node.eow==false){
return false;
}
curr=curr.children[idx];
}
return true;
}
public static void main(String[] args) {
String words[]={"a","the","any","there"};
for(int i=0;i<words.length;i++){
insert(words[i]);
}
System.out.println(search("an"));
System.out.println(search("them"));
}
}