-
Notifications
You must be signed in to change notification settings - Fork 0
/
letcode_1032_字符流.py
75 lines (64 loc) · 1.93 KB
/
letcode_1032_字符流.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
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
70
71
72
73
74
75
# -*- encoding: utf-8 -*-
"""
@File : letcode_1032_字符流.py
@Time : 2020/10/10 上午10:24
@Author : dididididi
@Email :
@Software: PyCharm
"""
import collections
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.Trie = {}
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
curr = self.Trie
for w in word:
if w not in curr:
curr[w] = {}
curr = curr[w]
curr['#'] = 1
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
curr = self.Trie
for w in word:
if w not in curr:
return False
if "#" in curr[w]:
return True
curr = curr[w]
return False
class StreamChecker:
def __init__(self, words):
self.trie = Trie()
self.stream = collections.deque([])
for word in set(words):
self.trie.insert(word[::-1])
def query(self, letter: str) -> bool:
self.stream.appendleft(letter)
return self.trie.search(self.stream)
if __name__ == '__main__':
streamChecker = StreamChecker(["cd","f","kl"])
streamChecker.query('a') # 返回false
streamChecker.query('b') # 返回false
streamChecker.query('c') # 返回false
streamChecker.query('d') # 返回true,因为'cd'在字词表中
streamChecker.query('e') # 返回false
streamChecker.query('f') # 返回true,因为'f'在字词表中
streamChecker.query('g') # 返回false
streamChecker.query('h') # 返回false
streamChecker.query('i') # 返回false
streamChecker.query('j') # 返回false
streamChecker.query('k') # 返回false
streamChecker.query('l') # 返回true,因为'kl'在字词表中。