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
52 lines (47 loc) · 1.13 KB
/
Stream of Characters.java
File metadata and controls
52 lines (47 loc) · 1.13 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
class StreamChecker {
TrieNode root;
Deque<Character> stream;
public StreamChecker(String[] words) {
root = new TrieNode('-');
stream = new ArrayDeque();
for (String word : words) {
TrieNode curr = root;
for (int i = word.length() - 1; i >= 0; i--) {
if (!curr.map.containsKey(word.charAt(i))) {
curr.map.put(word.charAt(i), new TrieNode(word.charAt(i)));
}
curr = curr.map.get(word.charAt(i));
}
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.map.containsKey(c)) {
return false;
}
curr = curr.map.get(c);
}
return curr.isWord;
}
}
class TrieNode {
char c;
Map<Character, TrieNode> map;
boolean isWord;
public TrieNode(char c) {
this.c = c;
map = new HashMap<>();
isWord = false;
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* boolean param_1 = obj.query(letter);
*/