Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
problem 211: Design Add and Search Words Data Structure
  • Loading branch information
sumanth-botlagunta committed Mar 19, 2023
commit 31b4c4aa377d8aeeef8b0068ed1c61e46ab7c6df
37 changes: 37 additions & 0 deletions python/design_add_and_search_words_data_structure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Trienode:
def __init__(self):
self.children = {}
self.word = False

class WordDictionary:

def __init__(self):
self.root = Trienode()


def addWord(self, word: str) -> None:
ptr = self.root
for ch in word:
if ch not in ptr.children:
ptr.children[ch] = Trienode()
ptr = ptr.children[ch]
ptr.word = True


def search(self, word: str) -> bool:
def dfs(j, root):
curr = root
for i in range(j, len(word)):
ch = word[i]
if ch == ".":
for child in curr.children.values():
if dfs(i+1, child):
return True
return False
else:
if ch not in curr.children:
return False
curr = curr.children[ch]
return curr.word
return dfs(0, self.root)