-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplementTrie.java
114 lines (102 loc) · 2.27 KB
/
ImplementTrie.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package ProjectFiles;
public class ImplementTrie {
BUGGY CODE
/**
* BUGGY CODE
* @param args
*/
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("somestring");
System.out.println(trie.search("key"));
System.out.println(trie.startsWith("some"));
System.out.println(trie.search("somestring"));
System.out.println(trie.search("some"));
System.out.println(trie.search("somestringg"));
System.out.println(trie.search("st"));
}
}
class TrieNode {
TrieNode[] children;
public TrieNode() {
children = new TrieNode[26];
}
}
class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
insertRec(word, root);
}
public void insertRec(String word, TrieNode node){
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(node.children == null){
node.children = new TrieNode[26];
}
if(node.children[c - 'a'] != null){
node = node.children[c - 'a'];
}
else{
node.children[c - 'a'] = new TrieNode();
node = node.children[c - 'a'];
}
}
}
// Returns if the word is in the trie.
public boolean search(String word) {
return searchRec(word, root);
}
public boolean searchRec(String word, TrieNode node){
boolean found = false;
int i = 0;
for(; i < word.length(); i++){
char c = word.charAt(i);
if(node.children == null){
break;
}
if(node.children[c - 'a'] != null){
node = node.children[c - 'a'];
}
else{
break;
}
}
if( i == word.length()){
found = true;
}
return found;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
return startsWithRec(prefix, root);
}
public boolean startsWithRec(String prefix, TrieNode node){
boolean found = false;
int i = 0;
for(; i < prefix.length(); i++){
char c = prefix.charAt(i);
if(root.children == null){
break;
}
if(root.children[c - 'a'] != null){
root = root.children[c - 'a'];
}
else{
break;
}
}
if( i == prefix.length()){
found = true;
}
return found;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");