leetcode-DictionaryTree

4. 字典树问题

使用list中表示字典树,Trie 中一般都含有大量的空链接,因此在绘制一棵单词查找树时一般会忽略空链接,同时为了方便理解我们可以画成这样:

image-20240531154404853

使用树形架构表示字典树

image-20240531154404853

使用dict表示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 使用dict表示Trie
class Trie:
def __init__(self):
self.lookup = {}

def insert(self, word: str) -> None:
tree = self.lookup
for a in word:
if a not in tree:
tree[a] = {}
tree = tree[a]
tree['#'] = '#'

def search(self, word: str) -> bool:
tree = self.lookup
# print(tree)
for a in word:
if a not in tree:
return False
tree = tree[a]

if '#' in tree:
return True
return False

def startsWith(self, prefix: str) -> bool:
tree = self.lookup
for a in prefix:
if a not in tree:
return False
tree = tree[a]
return True

使用class表示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 使用class方式
# 字典实现
class TrieNode(object):
def __init__(self):
self.children = {}
self.is_word = False

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

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.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word = True

def search_prefix(self, word):
node = self.root
for c in word:
if c not in node.children:
return None
node = node.children[c]
return node

def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.search_prefix(word)
return node is not None and 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
"""
return self.search_prefix(prefix) is not None