Skip to content

Commit f3f334e

Browse files
authored
Update Add and Search Word - Data structure design.py
1 parent d0e1a95 commit f3f334e

File tree

1 file changed

+29
-30
lines changed

1 file changed

+29
-30
lines changed

Add and Search Word - Data structure design.py

+29-30
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
class TrieNode:
2525
def __init__(self):
2626
self.children = {}
27-
self.is_word = False
27+
self.is_end = False
2828

2929
class WordDictionary(object):
3030

@@ -33,24 +33,41 @@ def __init__(self):
3333
Initialize your data structure here.
3434
"""
3535
self.root = TrieNode()
36-
3736

3837
def addWord(self, word):
3938
"""
4039
Adds a word into the data structure.
4140
:type word: str
4241
:rtype: void
4342
"""
44-
if not word:
45-
return
46-
4743
node = self.root
48-
for w in word:
49-
if w not in node.children:
50-
node.children[w] = TrieNode()
51-
52-
node = node.children[w]
53-
node.is_word = True
44+
for c in word:
45+
if c not in node.children:
46+
tmp = TrieNode()
47+
node.children[c] = tmp
48+
node = node.children[c]
49+
node.is_end = True
50+
51+
52+
def find(self, root, word):
53+
node = root
54+
for i in xrange(len(word)):
55+
if word[i] == '.':
56+
flag = False
57+
for x in node.children:
58+
if self.find(node.children[x], word[i+1:]):
59+
flag = True
60+
break
61+
if flag:
62+
return True
63+
else:
64+
return False
65+
else:
66+
if word[i] not in node.children:
67+
return False
68+
node = node.children[word[i]]
69+
70+
return node != None and node.is_end
5471

5572
def search(self, word):
5673
"""
@@ -59,25 +76,7 @@ def search(self, word):
5976
:rtype: bool
6077
"""
6178

62-
if not word:
63-
return False
64-
65-
self.res = False
66-
self.find(self.root, word)
67-
return self.res
68-
69-
def find(self, node, word):
70-
if not word:
71-
if node.is_word:
72-
self.res = True
73-
return
74-
elif word[0] == '.':
75-
for c in node.children:
76-
self.find(node.children[c], word[1:])
77-
else:
78-
if word[0] in node.children:
79-
self.find(node.children[word[0]], word[1:])
80-
79+
return self.find(self.root, word)
8180

8281

8382
# Your WordDictionary object will be instantiated and called as such:

0 commit comments

Comments
 (0)