-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1032.stream-of-characters.java
72 lines (61 loc) · 1.62 KB
/
1032.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* @lc app=leetcode id=1032 lang=java
*
* [1032] Stream of Characters
*/
// @lc code=start
class StreamChecker {
TrieNode root;
List<Character> stream;
class TrieNode {
boolean isWord;
TrieNode[] next;
TrieNode() {
isWord = false;
next = new TrieNode[26];
}
}
public StreamChecker(String[] words) {
root = new TrieNode();
buildTrie(words);
stream = new ArrayList<>();
}
void buildTrie(String[] words) {
for (String s : words) {
insert(s);
}
}
void insert(String s) {
TrieNode p = root;
// build trie but in reversed order for each word
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if (p.next[c - 'a'] == null) {
p.next[c - 'a'] = new TrieNode();
}
p = p.next[c - 'a'];
}
p.isWord = true;
}
public boolean query(char letter) {
stream.add(letter);
TrieNode p = root;
for (int i = stream.size() - 1; i >= 0; i--) {
char c = stream.get(i);
// return false immediately when we can't find c in Trie
if (p.next[c - 'a'] == null)
return false;
// find a word
if (p.next[c - 'a'].isWord)
return true;
p = p.next[c - 'a'];
}
return false;
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words); boolean param_1 =
* obj.query(letter);
*/
// @lc code=end