Add and Search Word - Data structure design

来源:互联网 发布:编程用什么电脑好 编辑:程序博客网 时间:2024/06/04 18:01

leetcode第211题,归类标签是字典树,但是看到讨论区解法还是挺多的。这里最不好处理的就是“.”的处理,这里“.”可以代表任意字符,也就意味着遍历到有点符号的时候需要把所有的当前节点下的子节点全部遍历出来,一一比较,这里比较考验技巧了,其中我看到有一种采用递归方法,单独写一个递归函数,我参考了一种更容易理解的方法。


在这份代码中,首先注意count,这里是用来记录单词结束的,和上一个程序有所不同,这个标记可以记录有多少个单词在这个节点结束,其实大同小异,在这题目中没有太大作用,但是简化了代码量。

关键是这里采用了一个很关键的地方就是用一个列表记录子节点,当遇到‘.’符号的时候,子节点不再是一个,而是一个集合,所以把所有的子节点全部加入列表中记录,而后遍历这个列表中的节点,遍历到最后,这个集合里只要有单词结束标志,就意味着找到了。

class TrieNode(object):    def __init__(self):        """        Initialize your data structure here.        """        self.count = 0        self.childern = {}class WordDictionary(object):    def __init__(self):        self.root = TrieNode()    def addWord(self, word):        node = self.root        for c in word:            if c in node.childern:                node = node.childern[c]            else:                newNode = TrieNode()                node.childern[c] = newNode                node = newNode        node.count += 1     def search(self, word):        nodes = [self.root]        for c in word:            subNode = []            for node in nodes:                if c == '.':                    subNode += node.childern.values()                elif c in node.childern:                    subNode.append(node.childern[c])            nodes = subNode        for node in nodes:            if node.count > 0:                return True        return False        # Your WordDictionary object will be instantiated and called as such:# wordDictionary = WordDictionary()# wordDictionary.addWord("word")# wordDictionary.search("pattern")



0 0