-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamChecker.java
More file actions
69 lines (61 loc) · 1.82 KB
/
StreamChecker.java
File metadata and controls
69 lines (61 loc) · 1.82 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
59
60
61
62
63
64
65
66
67
68
69
import java.util.LinkedList;
import java.util.Queue;
public class StreamChecker {
class Node{
Character c;
boolean end;
Node [] child;
public Node(Character c){
this.c = c;
end = false;
child = new Node[26];
}
}
Node root;
Queue<Node> pts;
private void insert(String s){
Node p = root;
int index = 0;
while(index < s.length()){
if(p.child[s.charAt(index) - 'a'] == null){
p.child[s.charAt(index) - 'a'] = new Node(s.charAt(index));
}
p = p.child[s.charAt(index) - 'a'];
index ++;
}
p.end = true;
}
public StreamChecker(String[] words) {
root = new Node(null);
for(String s: words){
insert(s);
}
pts = new LinkedList<>();
}
public boolean query(char letter) {
Queue<Node> remain = new LinkedList<>();
boolean ans = false;
while(!pts.isEmpty()){
Node pt = pts.poll();
if(pt.child[letter - 'a'] != null){
pt = pt.child[letter - 'a'];
ans = ans || pt.end;
remain.add(pt);
}
}
if(root.child[letter - 'a'] != null){
remain.add(root.child[letter - 'a']);
ans = ans || root.child[letter - 'a'].end;
}
pts = remain;
return ans;
}
public static void main(String[] args) {
String [] test = {"ab","ba","aaab","abab","baa"};
Character [] cs = {'a','a','a','a','a','b','a','b','a','b','b','b','a','b','a','b','b','b','b','a','b','a','b','a','a','a','b','a','a','a'};
StreamChecker sc = new StreamChecker(test);
for(Character c : cs){
System.out.println(sc.query(c));
}
}
}