leetcode-字典樹

字典樹

之前刷了不少leetcode的題目,現在把之前寫的代碼上傳了github:https://github.com/czy36mengfei/leetcode,歡迎大家下載、star。

知識拓展: 字典樹

Trie 又稱作字典樹、前綴樹。

Trie 的結構:

1、Trie 的設計很巧妙,它不像一般的字典那樣,把一整個單詞存在數據結構裏。Trie 利用單詞的前綴去匹配一棵樹,能匹配上,則說明這個字典裏有這個單詞;

2、Trie 的結構有那麼一點點像鏈表,只不過鏈表的 next 指針指向的是一個 Node 結點,而 Trienext 指針指向的是一個 Map

3、Trie 本身攜帶的內容僅僅只是 isWord 這樣一個布爾型變量,而沿着 next 指針一路走下來的路徑,就能表示一個單詞。

下面是一個 Trie 樹的基本結構:

class Trie(object):
    class Node:
        def __init__(self):
            self.is_word = False  # 是一個單詞結尾的標誌
            self.dict = dict()

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = Trie.Node()

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: None
        """
        node = self.root
        for c in word:
            if c not in node.dict:
                node.dict[c] = Trie.Node()
            node = node.dict[c]
        node.is_word = True


    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
        for c in word:
            if c not in node.dict:
                return False
            else:
                node = node.dict[c]
        return node.is_word

    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 c in prefix:
            if c not in node.dict:
                return False
            else:
                node = node.dict[c]
        return True

Trie的添加操作:

   def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: None
        """
        node = self.root
        for c in word:
            if c not in node.dict:
                node.dict[c] = Trie.Node()
            node = node.dict[c]
        node.is_word = True

Trie的查詢操作:

1、理解 Trie 的查詢只與待查詢的字符串的長度有關

2、下面這個方法查詢整個單詞在 Trie 中是否存在,所以在路徑匹配完成以後,一定不要忘了判斷匹配到的那個結點的 isWord 屬性,如果它是一個單詞的結尾,才返回 True

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
        for c in word:
            if c not in node.dict:
                return False
            else:
                node = node.dict[c]
        return node.is_word

Trie 的前綴查詢操作

前綴查詢就更簡單了,此時不需要判斷 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 c in prefix:
            if c not in node.dict:
                return False
            else:
                node = node.dict[c]
        return True

每日音樂:http://music.163.com/#/m/song?id=22840606

每日一題

添加與搜索單詞 - 數據結構設計

設計一個支持以下兩種操作的數據結構:

void addWord(word)
bool search(word)
search(word) 可以搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。

示例:

addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(".ad") -> true
search(“b…”) -> true
說明:

你可以假設所有單詞都是由小寫字母 a-z 組成的。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-and-search-word-data-structure-design

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章