-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.py
More file actions
31 lines (27 loc) · 812 Bytes
/
Trie.py
File metadata and controls
31 lines (27 loc) · 812 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
29
30
31
from collections import defaultdict
class TrieNode(object):
def __init__(self):
self.children = defaultdict(TrieNode)
self.is_word = False
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self,word):
cur = self.root
for char in word:
cur = cur.children[char]
cur.is_word = True
def search(self,word):
cur = self.root
for char in word:
cur = cur.children.get(char,None)
if cur is None:
return False
return cur.is_word
def startWith(self,prefix):
cur = self.root
for char in prefix:
cur = cur.children.get(char,None)
if cur is None:
return False
return True