-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1032. Stream of Characters.java
55 lines (47 loc) · 1.3 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
class StreamChecker {
class Node{
/* suffix trie */
Node[] childs = new Node[26];
boolean isEnd = false;
}
private final Node root;
private final StringBuilder sb;
public StreamChecker(String[] words)
{
root = new Node();
sb = new StringBuilder();
for(String s : words)
{
Node curr = root;
for(int i = s.length()-1; i >= 0; i--)
{
char ch = s.charAt(i);
if(curr.childs[ch-'a'] == null)
{
curr.childs[ch-'a'] = new Node();
}
curr = curr.childs[ch-'a'];
}
curr.isEnd = true;
}
}
public boolean query(char letter) {
sb.append(letter);
Node curr = root;
for(int i = sb.length()-1; i >= 0; i--)
{
char ch = sb.charAt(i);
curr = curr.childs[ch-'a'];
if(curr == null)
return false;
if(curr.isEnd == true)
return true;
}
return false;
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* boolean param_1 = obj.query(letter);
*/