关于前缀树基础知识就不介绍了,通俗总结就是从根节点出发,每个节点都有两个属性,一个是这个节点的所有子节点(python3用一个字典记录这个节点所有后续节点即可)和一个标志,标志是否是一个字符串的结束。对于前缀树而言通常需要有查询与插入两种操作。查询的话就是从根节点出发,依次查找根节点的子节点是否有对应的字符,直到字符结束。插入的话也是从根节点出发,依次查找当前节点的子节点是否有对应的字符,有就不需要重新生成,没有的话就重新生成一个前缀树节点,直到最后一个字符插入完毕。具体实现如下所示:
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.is_word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.root
for w in word:
cur = cur.children[w]
cur.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
cur = self.root
for w in word:
if w not in cur.children:
return False
cur = cur.children[w]
return cur.is_word
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur = self.root
for w in prefix:
if w not in cur.children:
return False
cur = cur.children[w]
return True
关于前缀树的应用,参见力扣472
前缀树实现:
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.is_word = False
class Trie:
def __init__(self,words):
self.root = TrieNode()
for word in words:
self.insert(word)
def insert(self,word:str):
cur = self.root
for item in word:
cur = cur.children[item]
cur.is_word = True
class Solution:
def findAllConcatenatedWordsInADict(self, words:list):
Trie_ = Trie(words)
ans = []
def dfs(i,word,cur,is_cut):
if i == len(word):
return cur.is_word and is_cut
if cur.is_word:
if dfs(i,word,Trie_.root,True):
return True
if word[i] not in cur.children:
return False
else:
return dfs(i+1,word,cur.children[word[i]],is_cut)
for word in words:
if dfs(0,word,Trie_.root,False):
ans.append(word)
return ans