-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordSearch.py
executable file
·31 lines (24 loc) · 928 Bytes
/
WordSearch.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
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word):
current_node = self.root
for character in word:
current_node = current_node.children.setdefault(character, TrieNode())
current_node.is_word = True
def search(self, word):
def dfs(node, index):
if index == len(word):
return node.is_word
if word[index] == ".":
for child in node.children.values():
if dfs(child, index+1):
return True
if word[index] in node.children:
return dfs(node.children[word[index]], index+1)
return False
return dfs(self.root, 0)