LeetCode:208. Implement Trie (Prefix Tree)

题目描述

Implement a trie with insert, search, and startsWith methods.

Example:

1
2
3
4
5
6
7
8
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

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

Trie树能够存储字符串,它的每一个节点都代表了一个字母,结构如下所示:

img

上图中,存放了at、bee、ben、bt、q五个字符串。其中绿色代表着字符串的结束,它可以出现在树的非叶子节点。

因此对于每个节点,需要存放其值,子节点以及是否位字符串的结束,其定义如下:

1
2
3
4
5
class Node:
def __init__(self, val):
self.val = val
self.next = []
self.end = False

在进行insert(‘bed’)的时候,会从最顶的节点开始向下查找,如果查找到’b’,那么就会在这个’b’节点继续往下查找’e’,如果也有的话继续在’e’查找’d’ 。但是如果一开始没有查找到’b’,则会新创建一个节点’b’,然后在这个新节点下面继续查找’e’(虽然一定是找不到的),找不到的话创建’e’ ,以此类推。

在进行search的时候,也会从头节点开始向下进行查找,但是如果找不到,那么会直接返回False。如果完整地找到了这个字符串,还需要看该字符串的最后一个节点的end是否为True,如果是则返回True,否则返回False。

startswith操作和search操作基本一致,但是它不需要检查字符串的最后一个节点的end状态。

代码实现

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Node:
def __init__(self, val):
self.val = val
self.next = []
self.end = False

class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.start = Node(-1)

def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
this = self.start
index = 0

while index < len(word):
find = False
for i in this.next:
if i.val == word[index]:
find = True
this = i
index += 1
break
if find == False:
newNode = Node(word[index])
this.next.append(newNode)
this = newNode
index += 1

this.end = True

def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
this = self.start
index = 0

while index < len(word):
find = False
for i in this.next:
if i.val == word[index]:
find = True
this = i
index += 1
break
if find == False:
return False

if this.end == True:
return True
else:
return False


def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
this = self.start
index = 0

while index < len(prefix):
find = False
for i in this.next:
if i.val == prefix[index]:
find = True
this = i
index += 1
break
if find == False:
return False

return True