forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
implement-trie-ii-prefix-tree.py
73 lines (66 loc) · 1.86 KB
/
implement-trie-ii-prefix-tree.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Time: ctor: O(1)
# insert: O(n)
# count_word: O(n)
# count_prefix: O(n)
# erase: O(n)
# Space: O(t), t is the number of nodes in trie
class Node:
def __init__(self):
self.children = [None]*26
self.pcnt = 0
self.cnt = 0
class Trie(object):
def __init__(self):
self.__trie = Node()
def insert(self, word):
"""
:type word: str
:rtype: None
"""
curr = self.__trie
curr.pcnt += 1
for c in word:
if curr.children[ord(c)-ord('a')] is None:
curr.children[ord(c)-ord('a')] = Node()
curr = curr.children[ord(c)-ord('a')]
curr.pcnt += 1
curr.cnt += 1
def countWordsEqualTo(self, word):
"""
:type word: str
:rtype: int
"""
curr = self.__trie
for c in word:
if curr.children[ord(c)-ord('a')] is None:
return 0
curr = curr.children[ord(c)-ord('a')]
return curr.cnt
def countWordsStartingWith(self, prefix):
"""
:type prefix: str
:rtype: int
"""
curr = self.__trie
for c in prefix:
if curr.children[ord(c)-ord('a')] is None:
return 0
curr = curr.children[ord(c)-ord('a')]
return curr.pcnt
def erase(self, word):
"""
:type word: str
:rtype: None
"""
cnt = self.countWordsEqualTo(word)
if not cnt:
return
curr = self.__trie
curr.pcnt -= 1
for c in word:
if curr.children[ord(c)-ord('a')].pcnt == 1:
curr.children[ord(c)-ord('a')] = None # delete all unused nodes
return
curr = curr.children[ord(c)-ord('a')]
curr.pcnt -= 1
curr.cnt -= 1