zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 69

    Add and Search Word - Data structure design

    要点:类似的题做过n多遍了,不容易记的地方就是call递归函数之前要创建结点表示当前的字符。当递归过界的时候,表示没有当前字符,所以直接返回而不创建+进一步递归
    错误点:注意None and如果hit None的branch整个式子返回None而不是False,当然如果作为if的条件是无所谓的,因为None自动转为False。但是作为返回结果就不对了。

    class WordDictionary(object):
        class TrieNode:
            def __init__(self):
                self.neighbors = [None]*26
                self.isLeaf = False
            
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.root = self.TrieNode()
    
        def addWord(self, word):
            """
            Adds a word into the data structure.
            :type word: str
            :rtype: void
            """
            def addRec(root, start, word):
                n = len(word)
                if start==n:
                    root.isLeaf = True
                    return
                
                c = ord(word[start])-ord('a')
                if not root.neighbors[c]:
                    root.neighbors[c] = self.TrieNode()
                addRec(root.neighbors[c], start+1, word)
            
            addRec(self.root, 0, word)
            
    
        def search(self, word):
            """
            Returns if the word is in the data structure. A word could
            contain the dot character '.' to represent any one letter.
            :type word: str
            :rtype: bool
            """
            def searchRec(root, start, word):
                n = len(word)
                if start==n:
                    if root.isLeaf:
                        return True
                    else:
                        return False
                
                if word[start]=='.':
                    for t in root.neighbors:
                        if t and searchRec(t, start+1, word):
                            return True
                    return False
                else:
                    c = ord(word[start])-ord('a')
                    return root.neighbors[c] is not None and searchRec(root.neighbors[c], start+1, word)
            return searchRec(self.root, 0, word)
            
    
    # Your WordDictionary object will be instantiated and called as such:
    # wordDictionary = WordDictionary()
    # wordDictionary.addWord("word")
    # wordDictionary.search("pattern")
    
    
  • 相关阅读:
    一线架构师实践指南第三编阅读笔记
    学习七
    《信息领域热词分析》,如何设计编码实现六种质量属性战术
    学习六
    一线架构师实践指南第二部分阅读笔记
    学习五
    echarts实现省市区地图下钻
    python提取文本关键词
    后缀自动机复习笔记
    bzoj 1552
  • 原文地址:https://www.cnblogs.com/absolute/p/5690355.html
Copyright © 2011-2022 走看看