-
Notifications
You must be signed in to change notification settings - Fork 277
/
StreamOfCharacters.java
60 lines (51 loc) · 1.18 KB
/
StreamOfCharacters.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
class StreamChecker {
private class TrieNode{
private TrieNode[] children =null;
private boolean isLeaf;
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);
}
}
private void addWord(String word){
TrieNode it = root;
for(int i=word.length()-1;i>=0;i--){ // Iterating in revese order
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;
}
public boolean query(char letter) {
queryStr.append(letter);
return search(queryStr.toString());
}
private boolean search(String queryStr){
TrieNode it = root;
for(int i=queryStr.length()-1;i>=0;i--){
char c = queryStr.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;
}
}