Skip to content

Commit 29267fe

Browse files
authored
Create implement-trie-ii-prefix-tree.py
1 parent 0ef05c2 commit 29267fe

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Time: ctor: O(1)
2+
# insert: O(n)
3+
# count_word: O(n)
4+
# count_prefix: O(n)
5+
# erase: O(n)
6+
# Space: O(t), t is the number of nodes in trie
7+
8+
class Node:
9+
def __init__(self):
10+
self.children = [None]*26
11+
self.pcnt = 0
12+
self.cnt = 0
13+
14+
class Trie(object):
15+
16+
def __init__(self):
17+
self.__trie = Node()
18+
19+
def insert(self, word):
20+
"""
21+
:type word: str
22+
:rtype: None
23+
"""
24+
curr = self.__trie
25+
curr.pcnt += 1
26+
for c in word:
27+
if curr.children[ord(c)-ord('a')] is None:
28+
curr.children[ord(c)-ord('a')] = Node()
29+
curr = curr.children[ord(c)-ord('a')]
30+
curr.pcnt += 1
31+
curr.cnt += 1
32+
33+
def countWordsEqualTo(self, word):
34+
"""
35+
:type word: str
36+
:rtype: int
37+
"""
38+
curr = self.__trie
39+
for c in word:
40+
if curr.children[ord(c)-ord('a')] is None:
41+
return 0
42+
curr = curr.children[ord(c)-ord('a')]
43+
return curr.cnt
44+
45+
def countWordsStartingWith(self, prefix):
46+
"""
47+
:type prefix: str
48+
:rtype: int
49+
"""
50+
curr = self.__trie
51+
for c in prefix:
52+
if curr.children[ord(c)-ord('a')] is None:
53+
return 0
54+
curr = curr.children[ord(c)-ord('a')]
55+
return curr.pcnt
56+
57+
def erase(self, word):
58+
"""
59+
:type word: str
60+
:rtype: None
61+
"""
62+
cnt = self.countWordsEqualTo(word)
63+
if not cnt:
64+
return
65+
curr = self.__trie
66+
curr.pcnt -= 1
67+
for c in word:
68+
if curr.children[ord(c)-ord('a')].pcnt == 1:
69+
curr.children[ord(c)-ord('a')] = None # delete all unused nodes
70+
return
71+
curr = curr.children[ord(c)-ord('a')]
72+
curr.pcnt -= 1
73+
curr.cnt -= 1

0 commit comments

Comments
 (0)