LeetCode 208 [Implement Trie (Prefix Tree)]

原題

實(shí)現(xiàn)一個(gè) Trie,包含 insert, search, 和 startsWith 這三個(gè)方法。

樣例

insert("lintcode")
search("code") # return false
startsWith("lint") # return true
startsWith("linterror") # return false
insert("linterror")
search("lintcode) # return true
startsWith("linterror") # return true

解題思路

  • 首先,定義一個(gè)trie樹節(jié)點(diǎn),包含當(dāng)前的char和isWord布爾值
  • 注意根節(jié)點(diǎn)不包含字符,每個(gè)節(jié)點(diǎn)最多有26叉
  • Insert - 即遍歷單詞的每個(gè)字符,逐層查找,有則繼續(xù),沒有就創(chuàng)建一個(gè)新的TrieNode,左后一位IsWord = True
  • Search - 同理,遍歷單詞每個(gè)字符,逐層查找,沒有立即返回False,找到最后一個(gè)TrieNode,則返回 TrieNode.IsWord

完整代碼

class TrieNode(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.children = {}
        self.IsWord = False
        

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        node = self.root
        for letter in word:
            child = node.children.get(letter)
            if child is None:
                child = TrieNode()
                node.children[letter] = child
            node = child
        node.IsWord = True

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
        for letter in word:
            node = node.children.get(letter)
            if node is None:
                return False
        return node.IsWord

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie
        that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node = self.root
        for letter in prefix:
            node = node.children.get(letter)
            if node is None:
                return False
        return True

# Your Trie object will be instantiated and called as such:
# trie = Trie()
# trie.insert("somestring")
# trie.search("key")
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容