Skip to content

Commit 66c0616

Browse files
committed
Adding Leetcode Problem 208. Implement Trie
1 parent 7ef4ae8 commit 66c0616

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Implement a trie with insert, search, and startsWith methods.
2+
3+
# Example:
4+
5+
# Trie trie = new Trie();
6+
# trie.insert("apple");
7+
# trie.search("apple"); // returns true
8+
# trie.search("app"); // returns false
9+
# trie.startsWith("app"); // returns true
10+
# trie.insert("app");
11+
# trie.search("app"); // returns true
12+
13+
class TrieNode:
14+
def __init__(self, val):
15+
self.val = val
16+
self.isEnd = False
17+
self.children = [None for i in range(26)]
18+
class Trie:
19+
def __init__(self):
20+
"""
21+
Initialize your data structure here.
22+
"""
23+
self.root = TrieNode('*')
24+
25+
26+
def insert(self, word: str) -> None:
27+
"""
28+
Inserts a word into the trie.
29+
"""
30+
node = self.root
31+
for c in word:
32+
x = ord(c) - ord('a')
33+
if node.children[x] is None:
34+
node.children[x] = TrieNode(c)
35+
node = node.children[x]
36+
node.isEnd = True
37+
38+
def search(self, word: str) -> bool:
39+
"""
40+
Returns if the word is in the trie.
41+
"""
42+
node = self.root
43+
for c in word:
44+
x = ord(c) - ord('a')
45+
if node.children[x] is not None:
46+
node = node.children[x]
47+
else:
48+
return False
49+
return node.isEnd
50+
51+
52+
def startsWith(self, prefix: str) -> bool:
53+
"""
54+
Returns if there is any word in the trie that starts with the given prefix.
55+
"""
56+
node = self.root
57+
for c in prefix:
58+
x = ord(c) - ord('a')
59+
if node.children[x] is not None:
60+
node = node.children[x]
61+
else:
62+
return False
63+
return True
64+
65+
66+
# Your Trie object will be instantiated and called as such:
67+
# obj = Trie()
68+
# obj.insert(word)
69+
# param_2 = obj.search(word)
70+
# param_3 = obj.startsWith(prefix)

0 commit comments

Comments
 (0)