-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTrie.py
More file actions
63 lines (57 loc) · 1.88 KB
/
Trie.py
File metadata and controls
63 lines (57 loc) · 1.88 KB
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
# 208. Implement Trie - Prefix Tree
# 定义一个trie树节点,包含当前的children和isWord布尔值。
# children是一个字典,key为一个字符,value为这个字符对应的后缀所组成的TrieNode。
# isWord表示是否有一个word到此node结束。
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = {}
self.isWord = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
# 即遍历单词的每个字符,逐层查找,有则继续,没有就创建一个新的TrieNode,最后一位IsWord = True
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
node = self.root
for letter in word:
child = node.children.get(letter)
if not child:
child = TrieNode()
node.children[letter] = child
node = child
node.isWord = True
# 遍历单词每个字符,逐层查找,没有立即返回False,找到最后一个TrieNode,则返回 TrieNode.isWord
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for letter in word:
node = node.children.get(letter)
if not node:
return False
return node.isWord
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for letter in prefix:
node = node.children.get(letter)
if not node:
return False
return True