-
Notifications
You must be signed in to change notification settings - Fork 0
/
211.py
98 lines (79 loc) · 2.44 KB
/
211.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = ['"wuyadong" <[email protected]>']
from collections import deque
class TrieNode(object):
def __init__(self):
self.val = None
self.is_end = False
self.children = dict()
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
p = self.root
for c in word:
if c not in p.children:
node = TrieNode()
node.val = c
p.children[c] = node
p = p.children[c]
p.is_end = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could
contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
p = self.root
queue = deque()
queue.append(p)
queue.append(None)
for c in word:
if len(queue) <= 1:
return False
while len(queue) > 0:
node = queue.popleft()
if node is not None:
if c == '.':
for key, child in node.children.items():
queue.append(child)
else:
if c in node.children:
queue.append(node.children[c])
else:
queue.append(None)
break
while len(queue) > 0:
node = queue.popleft()
if node is not None and node.is_end:
return True
return False
if __name__ == "__main__":
word_dict = WordDictionary()
word_dict.addWord("a")
print word_dict.search(".")
# word_dict.addWord("ran")
# word_dict.addWord("rune")
# word_dict.addWord("runner")
# word_dict.addWord("runs")
# word_dict.addWord("add")
# word_dict.addWord("adds")
# word_dict.addWord("adder")
# word_dict.addWord("addee")
#
# print word_dict.search("........")
# print word_dict.search("..n.r")
# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern")