939. Stream Suffix Watch
A radio monitor listens to a stream of lowercase letters that arrive one at a time, and it must raise an alarm whenever the most recent letters spell one of its watched words. Build the class SuffixWatch.
The constructor SuffixWatch(words) receives the list of watched words (repeats are allowed). The method query(letter) appends letter to the end of the stream heard so far and returns true if some non-empty suffix of the whole stream, read in order, is exactly equal to one of the watched words; otherwise it returns false. The stream is never cleared between calls.
Each call must take time proportional to the length of the longest watched word, not to the number of words.
Example 1
- Input:
- operations = ["SuffixWatch","query","query","query","query","query","query"]arguments = [[["bark","ark","lm"]],["x"],["b"],["a"],["r"],["k"],["l"]]
- Output:
- [null,false,false,false,false,true,false]
- Explanation:
Only after the fifth letter does the stream 'xbark' end with a watched word ('bark', and also 'ark'); every other call answers false.
Example 2
- Input:
- operations = ["SuffixWatch","query","query","query","query","query","query","query","query"]arguments = [[["zig","gz"]],["z"],["i"],["g"],["z"],["g"],["z"],["i"],["g"]]
- Output:
- [null,false,false,true,true,false,true,false,true]
- Explanation:
The third call completes 'zig', the fourth and sixth calls complete 'gz' (streams 'zigz' and 'zigzgz'), and the last call completes 'zig' again.
Example 3
- Input:
- operations = ["SuffixWatch","query","query"]arguments = [[["q"]],["p"],["q"]]
- Output:
- [null,false,true]
- Explanation:
The one-letter word 'q' matches as soon as the letter q arrives.
Constraints
1 ≤ words.length ≤ 2000
1 ≤ words[i].length ≤ 200
words[i] and letter are lowercase English letters
At most 40000 calls to query
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(L) per query
- Space
- O(total word length)