• 边工作边刷题: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")
    
    
  • 相关阅读:
    《jmeter:菜鸟入门到进阶系列》
    Jmeter下载时Binaries和Source两类包的区别
    MySQL5.7 四种日志文件
    Windows下配置nginx+php(wnmp)
    回望2018,计划2019
    C# 单元测试(入门)
    C# 中out,ref,params参数的使用
    C# 程序运行中的流程控制
    Nacos(五):多环境下如何“读取”Nacos中相应的配置
    Nacos(四):SpringCloud项目中接入Nacos作为配置中心
  • 原文地址:https://www.cnblogs.com/absolute/p/5690355.html
Copyright © 2020-2023  润新知