LeetCode 1032. Stream of Characters

题目

Implement the StreamChecker class as follows:

  • StreamChecker(words): Constructor, init the data structure with the given words.
  • query(letter): returns true if and only if for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
streamChecker.query('a'); // return false
streamChecker.query('b'); // return false
streamChecker.query('c'); // return false
streamChecker.query('d'); // return true, because 'cd' is in the wordlist
streamChecker.query('e'); // return false
streamChecker.query('f'); // return true, because 'f' is in the wordlist
streamChecker.query('g'); // return false
streamChecker.query('h'); // return false
streamChecker.query('i'); // return false
streamChecker.query('j'); // return false
streamChecker.query('k'); // return false
streamChecker.query('l'); // return true, because 'kl' is in the wordlist

Note:

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 2000
  • Words will only consist of lowercase English letters.
  • Queries will only consist of lowercase English letters.
  • The number of queries is at most 40000.

思路

Python by search in Trie [w/ Visualization]

代码

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
from collections import defaultdict

class TrieNode:
def __init__(self):
self.dict = defaultdict(TrieNode)
self.is_word = False

class StreamChecker:

def __init__(self, words: List[str]):
'''
Build a trie for each word in reversed order
'''

# for user query record, init as empty string
self.prefix = ''

# for root node of trie, init as empty Trie
self.trie = TrieNode()

for word in words:
cur = self.trie
# make word in reverse order
word = word[::-1]
for char in word:
cur = cur.dict[char]
# mark this trie path as a valid word
cur.is_word = True


def query(self, letter: str) -> bool:
'''
Search user input in trie with reversed order
'''
self.prefix += letter
cur = self.trie
for char in reversed(self.prefix):
if char not in cur.dict:
# current char not in Trie, impossible to match words
break
cur = cur.dict[char]
if cur.is_word:
# user input match a word in Trie
return True
# No match
return False



# Your StreamChecker object will be instantiated and called as such:
# obj = StreamChecker(words)
# param_1 = obj.query(letter)