forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.py
More file actions
executable file
·87 lines (70 loc) · 1.64 KB
/
trie.py
File metadata and controls
executable file
·87 lines (70 loc) · 1.64 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
class Node(object):
def __init__(self):
self.children = {}
self.isEnd = False
def get(self, char):
if char in self.children:
return self.children[char]
else:
return None
def set(self, char):
if char in self.children:
return self.children[char]
else:
self.children[char] = Node()
return self.children[char]
def remove(self, char):
self.children.pop(char, None)
return len(self.children)==0
class Trie(object):
def __init__(self):
self.root = Node()
def insert(self, word):
curr = self.root
for i in xrange(len(word)):
c = word[i]
node = curr.get(c)
if node is None: node = curr.set(c)
if i==len(word)-1: node.isEnd = True
curr = node
def search(self, word):
curr = self.root
for i in xrange(len(word)):
c = word[i]
node = curr.get(c)
if node is None: return False
if i==len(word)-1: return node.isEnd
curr = node
def remove(self, word):
curr = self.root
stack = []
for i in xrange(len(word)):
c = word[i]
node = curr.get(c)
#the word does not exist
if node is None: return
stack.append((curr, c))
curr = node
#if the last node has other link
#just set isEnd to False
if len(curr.children)>0:
curr.isEnd = False
return
while stack and len(stack)>0:
node, c = stack.pop()
emptyAfterRemove = node.remove(c)
if not emptyAfterRemove: break
trie = Trie()
trie.insert('abc')
trie.insert('abgl')
trie.insert('cdf')
trie.insert('abcd')
trie.insert('lmn')
print trie.search('abc')
print trie.search('abcd')
trie.remove('abc')
print trie.search('abc')
trie.remove('abgl')
print trie.search('abgl')
trie.remove('abcd')
print trie.search('abcd')