-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path208.py
More file actions
28 lines (24 loc) · 872 Bytes
/
Copy path208.py
File metadata and controls
28 lines (24 loc) · 872 Bytes
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
class Trie:
class TrieNode:
def __init__(self):
self.is_end = False
self.next = [None for _ in range(26)]
def __init__(self):
self.root = self.TrieNode()
def insert(self, word: str) -> None:
node = self.root
for w in word:
if not node.next[ord(w) - ord('a')]:
node.next[ord(w) - ord('a')] = self.TrieNode()
node = node.next[ord(w) - ord('a')]
node.is_end = True
def search(self, word: str, search: bool = True) -> bool:
node = self.root
for w in word:
if node.next[ord(w) - ord('a')]:
node = node.next[ord(w) - ord('a')]
else:
return False
return node.is_end if search else True
def startsWith(self, prefix: str) -> bool:
return self.search(prefix, False)