Skip to content

Commit b161479

Browse files
authored
Create Implement Trie (Prefix Tree) - Leetcode 208.py
1 parent 804021b commit b161479

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Trie:
2+
def __init__(self):
3+
self.trie = {}
4+
5+
def insert(self, word: str) -> None:
6+
d = self.trie
7+
8+
for c in word:
9+
if c not in d:
10+
d[c] = {}
11+
d = d[c]
12+
13+
d['.'] = '.'
14+
15+
def search(self, word: str) -> bool:
16+
d = self.trie
17+
18+
for c in word:
19+
if c not in d:
20+
return False
21+
d = d[c]
22+
23+
return '.' in d
24+
25+
def startsWith(self, prefix: str) -> bool:
26+
d = self.trie
27+
28+
for c in prefix:
29+
if c not in d:
30+
return False
31+
d = d[c]
32+
33+
return True
34+
35+
# Time: O(N) where N is the length of any string
36+
# Space: O(T) where T is the total number of stored characters

0 commit comments

Comments
 (0)