-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd and Search Word - Data structure design.py
54 lines (49 loc) · 1.57 KB
/
Add and Search Word - Data structure design.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
class TrieNode(object):
def __init__(self):
self.isstring = False
self.nodes = {}
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
"""
cur = self.root
for c in word:
if c not in cur.nodes:
cur.nodes[c] = TrieNode()
cur = cur.nodes[c]
cur.isstring = 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
"""
def searchRec(word, pos, node):
if pos == len(word):
return node.isstring
else:
if word[pos] in node.nodes:
return searchRec(word, pos + 1, node.nodes[word[pos]])
elif word[pos] == '.':
for n in node.nodes.values():
if searchRec(word, pos + 1, n):
return True
return False
else:
return False
cur = self.root
return searchRec(word, 0, cur)
# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern")
##import:bad codes, using DFS templet