【leetcode】1032. Stream of Characters
生活随笔
收集整理的這篇文章主要介紹了
【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:
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.
解題思路:本題真對不起hard的級別,用字典樹即可解決。首先在init的時候,把words中所有word逆置后存入字典樹中;在query的時候,也有逆序的方式記錄所有歷史query過的值,同時判斷其前綴是否存在于字典樹中即可。
代碼如下:
class TreeNode(object):def __init__(self, x):self.val = xself.childDic = {}self.isword = Falseclass Trie(object):dic = {}def __init__(self):"""Initialize your data structure here."""self.root = TreeNode(None)self.dic = {}def insert(self,word):node = self.rootfor i in word:if i not in node.childDic:node.childDic[i] = TreeNode(i)node = node.childDic[i]node.isword = Truedef isExist(self,word):node = self.rootfor i in word:if i in node.childDic:node = node.childDic[i]if node.isword == True:return Trueelse:return Falseclass StreamChecker(object):q = ''def __init__(self, words):""":type words: List[str]"""self.t = Trie()for w in words:self.t.insert(w[::-1])def query(self, letter):""":type letter: str:rtype: bool"""#letter = letter[::-1]self.q = letter + self.qreturn self.t.isExist(self.q)?
轉載于:https://www.cnblogs.com/seyjs/p/10765511.html
總結
以上是生活随笔為你收集整理的【leetcode】1032. Stream of Characters的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: selenium环境配置
- 下一篇: HDU 5306 Gorgeous Se