-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path208.py
60 lines (53 loc) · 1.52 KB
/
208.py
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
'''
Date: 2020-08-11 11:41:09
LastEditors: FrankCast1e
LastEditTime: 2020-08-11 12:11:31
FilePath: /Leetcode/208.py
'''
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.tree_storage = dict()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
temp = self.tree_storage
for char in word:
if char not in temp:
temp[char] = dict()
temp[char]['ISWORD'] = False
temp = temp[char]
temp['ISWORD'] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
temp = self.tree_storage
for char in word:
if char not in temp:
return False
else:
temp = temp[char]
return temp['ISWORD']
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
temp = self.tree_storage
for char in prefix:
if char not in temp:
return False
else:
temp = temp[char]
return True
# Your Trie object will be instantiated and called as such:
trie = Trie()
trie.insert("apple")
print(trie.search("apple"))
print(trie.search("app"))
print(trie.startsWith("app"))
trie.insert("app")
print(trie.search("app"))