边工作边刷题: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")

posted @ 2016-05-29 05:38  absolute100  阅读(98)  评论(0编辑  收藏  举报