字典树是一种数据压缩结构。
我在写中科脚本时候已经用了字典树结构。
class Trie(object):
"""
字典树是一种数据压缩结构
"""
def __init__(self):
self.root = {}
# 单词每个字母逐层加入到字典树中
def insert(self, word):
p = self.root
for w in word:
if w not in p:
p[w] = {}
p = p[w]
p["$"] = 1
def find(self, prefix):
p = self.root
for w in prefix:
if w not in p:return None
p = p[w]
return p
def search(self, word):
node = self.find(word)
return node is not None and "$" in node
def start_with(self, prefix):
return self.find(prefix) is not None
trie = Trie()
trie.insert("abc")
print(trie.start_with("a"))
print(trie.search("abc"))
下面是基本的储存方法
“”"
“abc”,“abd”
{“a”:{“b”:{“c”:{"KaTeX parse error: Expected 'EOF', got '}' at position 4: ":1}̲, "d":{"":1}}}}
“”"