leetcode(208). Implement Trie (Prefix Tree)

来源:互联网 发布:淘宝店铺排行 编辑:程序博客网 时间:2024/06/11 18:05

problem

Implement a trie with insert, search, and startsWith methods.

Note: You may assume that all inputs are consist of lowercase letters
a-z.

solution

本题中主要介绍了前缀树(trie)的定义及应用,详见solution

class Trie(object):#使用dict作为树的节点,不用新建class    def __init__(self):        """        Initialize your data structure here.        """        #使用dict只需将出现的加入就行,没出现的不用管。        self.root = {}    def insert(self, word):        """        Inserts a word into the trie.        :type word: str        :rtype: void        """        root = self.root        for char in word:            root = root.setdefault(char,{})        root['$'] = True    def search(self, word):        """        Returns if the word is in the trie.        :type word: str        :rtype: bool        """        root = self.root        for char in word:            if char in root:                root = root[char]            else:                return False        return '$' in root    def startsWith(self, prefix):        """        Returns if there is any word in the trie that starts with the given prefix.        :type prefix: str        :rtype: bool        """        root = self.root        for char in prefix:            if char in root:                root = root[char]            else:                return False        return True

D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D