-
Notifications
You must be signed in to change notification settings - Fork 3
/
q0211.py
69 lines (56 loc) · 1.62 KB
/
q0211.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
from typing import Dict
class WordDictionary:
dic = {}
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
temp = self.dic
for char in word:
if char not in temp:
temp[char] = {}
temp = temp[char]
temp["End"] = True
def searchInSubDic(self, word:str, index:int, dic:Dict):
temp = dic
wordLen = len(word)
for i in range(index,wordLen):
char = word[i]
if char == ".":
for key in temp.keys():
if key != "End" and self.searchInSubDic(word, i + 1, temp[key]):
return True
return False
elif char not in temp:
return False
temp = temp[char]
if "End" in temp:
return True
else:
return False
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
return self.searchInSubDic(word, 0, self.dic)
obj = WordDictionary()
obj.addWord("a")
obj.addWord("a")
print(obj.search("."))
print(obj.search("a"))
print(obj.search("aa"))
print(obj.search("a"))
print(obj.search(".a"))
print(obj.search("a."))
# obj.addWord("bad")
# obj.addWord("dad")
# obj.addWord("mad")
# print(obj.search("pad"))
# print(obj.search("bad"))
# print(obj.search(".ad"))
# print(obj.search("b.."))