-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathStreamChecker.java
67 lines (58 loc) · 1.74 KB
/
StreamChecker.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
class StreamChecker {
private class TrieNode{
TrieNode[] children = null;
boolean isLeaf = false;
public TrieNode(){
children = new TrieNode[26];
}
}
private TrieNode root = null;
private StringBuilder queryStr = null;
public StreamChecker(String[] words) {
root = new TrieNode();
queryStr = new StringBuilder();
for(String word: words){
addWord(word);
}
}
// Updating words in trie reversing the words in the trie
private void addWord(String word){
TrieNode it = root;
for(int i=word.length()-1;i>=0;i--){
char c = word.charAt(i);
int index = c -'a';
if(it!=null && it.children[index]==null){
TrieNode newNode = new TrieNode();
it.children[index] = newNode;
}
it = it.children[index];
}
it.isLeaf = true;
}
// Searching for the words in trie in the reverse order
public boolean query(char letter) {
queryStr.append(letter);
return search(queryStr.toString());
}
private boolean search(String word){
TrieNode it = root;
for(int i=word.length()-1;i>=0;i--){
char c = word.charAt(i);
int index = c -'a';
if(it!=null && it.children[index]!=null){
it = it.children[index];
if(it.isLeaf){
return true;
}
} else{
return false;
}
}
return false;
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* boolean param_1 = obj.query(letter);
*/