Skip to content

Commit 29eb1ed

Browse files
committed
208
1 parent 68ff66d commit 29eb1ed

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Week07/208.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Trie:
2+
3+
def __init__(self):
4+
"""
5+
Initialize your data structure here.
6+
"""
7+
self.root = {}
8+
self.end_of_word = "#"
9+
10+
def insert(self, word: str) -> None:
11+
"""
12+
Inserts a word into the trie.
13+
"""
14+
node = self.root
15+
for char in word:
16+
node = node.setdefault(char, {})
17+
node[self.end_of_word] = self.end_of_word
18+
19+
def search(self, word: str) -> bool:
20+
"""
21+
Returns if the word is in the trie.
22+
"""
23+
node = self.root
24+
for char in word:
25+
if char not in node:
26+
return False
27+
node = node[char]
28+
return self.end_of_word in node
29+
30+
def startsWith(self, prefix: str) -> bool:
31+
"""
32+
Returns if there is any word in the trie that starts with the given prefix.
33+
"""
34+
node = self.root
35+
for char in prefix:
36+
if char not in node:
37+
return False
38+
node = node[char]
39+
return True

0 commit comments

Comments
 (0)