-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.py
63 lines (52 loc) · 1.58 KB
/
trie.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
61
62
63
# Create a Trie with dictionary
class TrieNode:
def __init__(self, char):
self.char = char
self.children = {}
self.isFullWord = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = TrieNode("")
# Time complexity: O(n), Space complexity: O(1)
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.head
for i, char in enumerate(word):
if char not in cur.children:
cur.children[char] = TrieNode(char)
cur = cur.children[char]
cur.pathHasWord = True
cur.isFullWord = True
cur.pathHasWord = True
# Time complexity: O(n), Space complexity: O(1)
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
cur = self.head
for char in word:
if char not in cur.children:
return False
cur = cur.children[char]
return cur.isFullWord
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur = self.head
for char in prefix:
if char not in cur.children:
return False
cur = cur.children[char]
return True
trie = Trie()
trie.insert("word")
print(trie.search("word"))
print(trie.startsWith("wo"))
print(trie.search("hi"))
print(trie.startsWith("h"))