题目
实现一个 Trie (前缀树),包含 insert
, search
, 和 startsWith
这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
- 可以假设所有的输入都是由小写字母
a-z
构成的。 - 保证所有输入均为非空字符串。
方案一(数组)
class Node:
def __init__(self, val):
self.val = val
self.is_word = False # 是否是一个词
self.children = [None] * 26
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node(None)
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
nodes = self.root.children
length = len(word)
for i, c in enumerate(word):
index = ord(c) - 97 # ord('a') == 97
if not nodes[index]:
nodes[index] = Node(c)
if i == length - 1:
nodes[index].is_word = True
nodes = nodes[index].children
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
nodes = self.root.children
length = len(word)
for i, c in enumerate(word):
index = ord(c) - 97
if not nodes[index]:
return False
if i == length - 1:
if nodes[index].is_word:
return True
else:
return False
nodes = nodes[index].children
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
nodes = self.root.children
length = len(prefix)
for i, c in enumerate(prefix):
index = ord(c) - 97
if not nodes[index]:
return False
if i == length - 1:
return True
nodes = nodes[index].children
方案二(Map)
class Trie:
def __init__(self):
"""
Initialize your data structure here.
'bed' -> {
'b': {
'e': {
'd': {
'is_word': True
}
}
}
}
"""
self.lookup = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.lookup
for c in word:
if c not in node:
node[c] = {}
node = node[c]
node['is_word'] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.lookup
for c in word:
if c not in node:
return False
node = node[c]
# 判断是否是单词
if 'is_word' in node:
return True
return False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.lookup
for c in prefix:
if c not in node:
return False
node = node[c]
return True
原文
https://leetcode-cn.com/explore/learn/card/trie/166/basic-operations/645/