題目
實現前綴樹的插入、搜索以及startwith
函數。
例子:
Trie trie = new Trie(); // 構建前綴樹
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
什麼是前綴樹
基本資料
參考資料:大白話講解前綴樹
概念:Trie樹,即字典樹,又稱單詞查找樹或鍵樹,是一種樹形結構,是一種哈希樹的變種。典型應用是用於統計和排序大量的字符串(但不僅限於字符串),所以經常被搜索引擎系統用於文本詞頻統計。它的優點是:最大限度地減少無謂的字符串比較,查詢效率比哈希表高。(其實就是想說他使用了哈希的思想)
我的理解
要理解什麼是前綴樹,請看下面這張圖。從根節點出發,每條邊代表一個字母,同時每個節點記錄這個節點是否是一個字符串的結尾。
那麼,每一個字符串,都是從根節點開始的,到某一個紅色節點結束。前綴樹就是這麼簡單的一棵樹!
使用Python實現前綴樹
我們首先定義節點的格式:
class Node:
def __init__(self):
self.isWord = False
self.next = dict()
每個節點利用isWord
記錄是否是一個字符串的結尾;然後用字典記錄該節點對應的邊代表的字符串。
完整的代碼如下:
class Node:
def __init__(self):
self.isWord = False
self.next = dict()
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
n = self.root
for c in word:
if c not in n.next:
n.next[c] = Node()
n = n.next[c]
n.isWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
res = False
n = self.root
for c in word:
if c not in n.next:
break
n = n.next[c]
else:
if n.isWord:
res = True
return res
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
n = self.root
for c in prefix:
if c not in n.next:
return False
n = n.next[c]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)