Skip to content

Commit 95b89d9

Browse files
committed
solve(w05): 208. Implement Trie (Prefix Tree)
1 parent 85a811c commit 95b89d9

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# https://leetcode.com/problems/implement-trie-prefix-tree/
2+
3+
from collections import defaultdict
4+
5+
6+
class TrieNode:
7+
def __init__(self):
8+
self.is_word = False
9+
self.children = defaultdict(TrieNode)
10+
11+
12+
class Trie:
13+
def __init__(self):
14+
self.root = TrieNode()
15+
16+
def insert(self, word: str) -> None:
17+
curr = self.root
18+
19+
for w in word:
20+
curr = curr.children[w]
21+
22+
curr.is_word = True
23+
24+
def search(self, word: str) -> bool:
25+
curr = self.root
26+
27+
for w in word:
28+
if w not in curr.children:
29+
return False
30+
curr = curr.children[w]
31+
32+
return curr.is_word
33+
34+
def startsWith(self, prefix: str) -> bool:
35+
curr = self.root
36+
37+
for p in prefix:
38+
if p not in curr.children:
39+
return False
40+
curr = curr.children[p]
41+
42+
return True
43+
44+
# Your Trie object will be instantiated and called as such:
45+
# obj = Trie()
46+
# obj.insert(word)
47+
# param_2 = obj.search(word)
48+
# param_3 = obj.startsWith(prefix)

0 commit comments

Comments
 (0)