forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStream of Characters.py
33 lines (29 loc) · 944 Bytes
/
Stream of Characters.py
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
class TrieNode:
def __init__(self):
self.children = {}
self.endOfWord = False
class StreamChecker:
def __init__(self, words: List[str]):
self.root = TrieNode()
self.qCur = self.root
self.stream = collections.deque()
cur = self.root
for word in words:
for i in range(len(word) - 1, -1, -1):
ch = word[i]
if ch not in cur.children:
cur.children[ch] = TrieNode()
cur = cur.children[ch]
cur.endOfWord = True
cur = self.root
def query(self, letter: str) -> bool:
self.stream.appendleft(letter)
cur = self.root
for ch in self.stream:
if ch not in cur.children:
return False
else:
cur = cur.children[ch]
if cur.endOfWord:
return True
return False