-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1032. Stream of Characters.java
More file actions
58 lines (51 loc) · 1.61 KB
/
1032. Stream of Characters.java
File metadata and controls
58 lines (51 loc) · 1.61 KB
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
class StreamChecker {
// build trie in reverse order
// query trie in normal order
// only query, at most, max length of trie. if not found stop query return false;
class TrieNode{
TrieNode[] child = new TrieNode[26];
boolean isWord;
}
TrieNode root;
int maxLen = 0;
List<Character> queries;
public StreamChecker(String[] words) {
root = new TrieNode();
queries = new ArrayList();
for(String word : words){
maxLen = Math.max(maxLen, word.length());
buildTree(word);
}
}
public boolean query(char letter) {
queries.add(letter);
TrieNode queryNode = root;
int size = queries.size();
int end = Math.min(size, maxLen);
for(int i = 1; i <= end; ++i){
int idx = queries.get(size - i) - 'a';
if(queryNode.child[idx] == null) return false;
queryNode = queryNode.child[idx];
if(queryNode.isWord) return true;
}
return false;
}
private void buildTree(String word){
TrieNode cur = root;
char[] chs = word.toCharArray();
int len = chs.length;
for(int i = len - 1; 0 <= i; --i){
int idx = chs[i] - 'a';
if(cur.child[idx] == null){
cur.child[idx] = new TrieNode();
}
cur = cur.child[idx];
}
cur.isWord = true;
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* boolean param_1 = obj.query(letter);
*/