forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
add-and-search-word-data-structure-design.py
45 lines (36 loc) · 1.26 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
# Time: O(min(n, h)), per operation
# Space: O(min(n, h))
class TrieNode(object):
# Initialize your data structure here.
def __init__(self):
self.is_string = False
self.leaves = {}
class WordDictionary(object):
def __init__(self):
self.root = TrieNode()
# @param {string} word
# @return {void}
# Adds a word into the data structure.
def addWord(self, word):
curr = self.root
for c in word:
if c not in curr.leaves:
curr.leaves[c] = TrieNode()
curr = curr.leaves[c]
curr.is_string = True
# @param {string} word
# @return {boolean}
# Returns if the word is in the data structure. A word could
# contain the dot character '.' to represent any one letter.
def search(self, word):
return self.searchHelper(word, 0, self.root)
def searchHelper(self, word, start, curr):
if start == len(word):
return curr.is_string
if word[start] in curr.leaves:
return self.searchHelper(word, start+1, curr.leaves[word[start]])
elif word[start] == '.':
for c in curr.leaves:
if self.searchHelper(word, start+1, curr.leaves[c]):
return True
return False