Skip to content

Commit 4dc7cf2

Browse files
committed
committed from zkp
1 parent d724780 commit 4dc7cf2

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

LeetCode/WordDictionary.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class WordDictionary(object):
2+
3+
def __init__(self):
4+
"""
5+
Initialize your data structure here.
6+
"""
7+
self.root = {}
8+
9+
def addWord(self, word):
10+
"""
11+
Adds a word into the data structure.
12+
:type word: str
13+
:rtype: None
14+
"""
15+
node = self.root
16+
for w in word:
17+
if w in node.keys():
18+
node = node[w]
19+
else:
20+
node[w] = {}
21+
node = node[w]
22+
node['end'] = True
23+
24+
def search(self, word, prevnode=None):
25+
"""
26+
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
27+
:type word: str
28+
:rtype: bool
29+
"""
30+
# if prevnode is None:
31+
node = self.root
32+
# else:
33+
# print('..')
34+
# node = prevnode
35+
for w in word:
36+
if w == '.':
37+
return any([self.search(word.replace('.', i, 1)) for i in node.keys() if i != 'end'])
38+
else:
39+
if w not in node.keys():
40+
return False
41+
else:
42+
node = node[w]
43+
return node.get('end') is not None
44+
# Your WordDictionary object will be instantiated and called as such:
45+
# obj = WordDictionary()
46+
# obj.addWord(word)
47+
# param_2 = obj.search(word)
48+
if __name__ == '__main__':
49+
t = WordDictionary()
50+
t.addWord('bad')
51+
t.addWord('dad')
52+
t.addWord('mad')
53+
assert not t.search("pad")
54+
assert t.search("bad")
55+
t.search("b..")

0 commit comments

Comments
 (0)