forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStream of Characters.java
More file actions
55 lines (48 loc) · 1.2 KB
/
Stream of Characters.java
File metadata and controls
55 lines (48 loc) · 1.2 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
class StreamChecker {
Deque<Character> stream;
TrieNode root;
public StreamChecker(String[] words) {
root = new TrieNode('-');
stream = new ArrayDeque<>();
Arrays.stream(words).forEach(word -> addWord(word));
}
public void addWord(String word) {
TrieNode curr = root;
for (int i = word.length() - 1; i >= 0; i--) {
char c = word.charAt(i);
if (curr.children[c - 'a'] == null) {
curr.children[c - 'a'] = new TrieNode(c);
}
curr = curr.children[c - 'a'];
}
curr.isWord = true;
}
public boolean query(char letter) {
stream.addFirst(letter);
TrieNode curr = root;
for (char c : stream) {
if (curr.isWord) {
return true;
}
if (curr.children[c - 'a'] == null) {
return false;
}
curr = curr.children[c - 'a'];
}
return curr.isWord;
}
class TrieNode {
char c;
TrieNode[] children;
boolean isWord;
public TrieNode(char c) {
this.c = c;
children = new TrieNode[26];
}
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* boolean param_1 = obj.query(letter);
*/