211. Add and Search Word Data structure design - English Version

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Nice and easy to understand the solution! Thank you Ricky!

shen-yusun
Автор

For people who is interested in Trie approach

class WordDictionary:
class TrieNode:
def __init__(self):
from string import ascii_lowercase
self.children = {ch:None for ch in ascii_lowercase}
self.word = False

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

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

def search(self, word: str) -> bool:
def backtracking(word, node, idx):
# (a) base case
if idx == len(word): return node.word

# (b) recursive case
# special case for problem
if word[idx] == '.':
for ch in node.children.keys():
if node.children[ch] and backtracking(word, node.children[ch], idx + 1):
return True
return False
else:
return node.children[word[idx]] and \
backtracking(word, node.children[word[idx]], idx + 1)

return backtracking(word, self.root, 0)

aunnfriends
Автор

class WordDictionary:
def __init__(self):
from collections import defaultdict
self.dic = defaultdict(list)

def addWord(self, word: str) -> None:


def search(self, word: str) -> bool:
size = len(word)
if size not in self.dic: return False
for item in self.dic[size]:
matched = True
for i in range(size):
if word[i] != '.' and word[i] != item[i]:
matched = False
break
if matched: return True
return False

Runtime: 132 ms, faster than 99.01% of Python3 online submissions for Design Add and Search Words Data Structure.
Memory Usage: 21.1 MB, less than 93.34% of Python3 online submissions for Design Add and Search Words Data Structure.

aunnfriends
Автор

lets brainstorm it, "drinks asian supersoda"

riverlance
welcome to shbcf.ru