Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit dcc11e6

Browse files
authored
Update Stream of Characters.java
1 parent b659134 commit dcc11e6

File tree

1 file changed

+26
-23
lines changed

1 file changed

+26
-23
lines changed

Hard/Stream of Characters.java

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
11
class StreamChecker {
2-
TrieNode root;
2+
33
Deque<Character> stream;
4+
TrieNode root;
45
public StreamChecker(String[] words) {
56
root = new TrieNode('-');
6-
stream = new ArrayDeque();
7-
for (String word : words) {
8-
TrieNode curr = root;
9-
for (int i = word.length() - 1; i >= 0; i--) {
10-
if (!curr.map.containsKey(word.charAt(i))) {
11-
curr.map.put(word.charAt(i), new TrieNode(word.charAt(i)));
12-
}
13-
curr = curr.map.get(word.charAt(i));
7+
stream = new ArrayDeque<>();
8+
Arrays.stream(words).forEach(word -> addWord(word));
9+
}
10+
11+
public void addWord(String word) {
12+
TrieNode curr = root;
13+
for (int i = word.length() - 1; i >= 0; i--) {
14+
char c = word.charAt(i);
15+
if (curr.children[c - 'a'] == null) {
16+
curr.children[c - 'a'] = new TrieNode(c);
1417
}
15-
curr.isWord = true;
18+
curr = curr.children[c - 'a'];
1619
}
20+
curr.isWord = true;
1721
}
1822

1923
public boolean query(char letter) {
@@ -23,25 +27,24 @@ public boolean query(char letter) {
2327
if (curr.isWord) {
2428
return true;
2529
}
26-
if (!curr.map.containsKey(c)) {
30+
if (curr.children[c - 'a'] == null) {
2731
return false;
2832
}
29-
curr = curr.map.get(c);
33+
curr = curr.children[c - 'a'];
3034
}
3135
return curr.isWord;
3236
}
33-
}
34-
35-
36-
class TrieNode {
37-
char c;
38-
Map<Character, TrieNode> map;
39-
boolean isWord;
4037

41-
public TrieNode(char c) {
42-
this.c = c;
43-
map = new HashMap<>();
44-
isWord = false;
38+
39+
class TrieNode {
40+
char c;
41+
TrieNode[] children;
42+
boolean isWord;
43+
44+
public TrieNode(char c) {
45+
this.c = c;
46+
children = new TrieNode[26];
47+
}
4548
}
4649
}
4750

0 commit comments

Comments
 (0)