Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

1032. Stream of Characters

Posted on 2020-07-08 | Edited on 2021-01-22

LeetCode

link
Trie

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
class StreamChecker {

class TrieNode {
boolean isWord;
TrieNode[] next = new TrieNode[26];
}

TrieNode root = new TrieNode();
StringBuilder sb = new StringBuilder();

public StreamChecker(String[] words) {
createTrie(words);
}

public boolean query(char letter) {
sb.append(letter);
TrieNode node = root;
for (int i = sb.length() - 1; i >= 0 && node != null; i--) {
char c = sb.charAt(i);
node = node.next[c - 'a'];
if (node != null && node.isWord) {
return true;
}
}
return false;
}

private void createTrie(String[] words) {
for (String s : words) {
TrieNode node = root;
int len = s.length();
for (int i = len - 1; i >= 0; i--) {
char c = s.charAt(i);
if (node.next[c - 'a'] == null) {
node.next[c - 'a'] = new TrieNode();
}
node = node.next[c - 'a'];
}
node.isWord = true;
}
}
}

<1…727374…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%