-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1804.py
58 lines (46 loc) · 1.43 KB
/
m1804.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Trie:
def __init__(self):
self.trie = {}
def insert(self, word: str) -> None:
curr = self.trie
for c in word :
if c not in curr :
curr[c] = {}
curr = curr[c]
if False in curr :
curr[False] += 1
else :
curr[False] = 1
def countWordsEqualTo(self, word: str) -> int:
curr = self.trie
for c in word :
if c not in curr :
return 0
curr = curr[c]
return curr.get(False, 0)
def countWordsStartingWith(self, prefix: str) -> int:
curr = self.trie
for c in prefix :
if c not in curr :
return 0
curr = curr[c]
return self.countAllFromHere(curr)
def countAllFromHere(self, trie: dict) -> int :
output = trie.get(False, 0)
for k in trie :
if k :
output += self.countAllFromHere(trie[k])
return output
def erase(self, word: str) -> None:
curr = self.trie
for c in word :
if c not in curr :
return
curr = curr[c]
curr[False] = curr.get(False, 1) - 1
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.countWordsEqualTo(word)
# param_3 = obj.countWordsStartingWith(prefix)
# obj.erase(word)