Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save mvallebr/178d536b2a0e83733b1ef9e9f6cf1c5f to your computer and use it in GitHub Desktop.

Select an option

Save mvallebr/178d536b2a0e83733b1ef9e9f6cf1c5f to your computer and use it in GitHub Desktop.
class Node(object):
def __init__(self, value: str):
self.value = value
self.children = {}
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node("*")
def addWord(self, word: str) -> None:
last = self.root
for i in range(len(word)):
if word[i] not in last.children:
last.children[word[i]] = Node(word[i+1]) if i+1 < len(word) else Node('*')
last = last.children[word[i]]
def search(self, word: str) -> bool:
def search_i(node: Node, index: int) -> bool:
if index == len(word):
return "*" == node.value
c = word[index]
if c != '.':
if c not in node.children:
return False
else:
return search_i(node.children[c], index + 1)
else:
for c, child in node.children.items():
if search_i(child, index + 1):
return True
return False
return search_i(self.root, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment