forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStream of Characters.java
42 lines (37 loc) · 1.07 KB
/
Stream of Characters.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
class StreamChecker {
class TrieNode {
boolean isWord;
TrieNode[] next = new TrieNode[26];
}
TrieNode root = new TrieNode();
StringBuilder sb = new StringBuilder();
public StreamChecker(String[] words) {
createTrie(words);
}
public boolean query(char letter){
sb.append(letter);
TrieNode node = root;
for(int i=sb.length()-1; i>=0 && node!=null; i--){
char ch = sb.charAt(i);
node = node.next[ch - 'a'];
if(node != null && node.isWord){
return true;
}
}
return false;
}
private void createTrie(String words[]){
for(String s : words){
TrieNode node = root;
int len = s.length();
for(int i = len-1; i>=0; i--){
char ch = s.charAt(i);
if(node.next[ch-'a'] == null){
node.next[ch - 'a'] = new TrieNode();
}
node = node.next[ch - 'a'];
}
node.isWord = true;
}
}
}