Leetcode Problem 676: Implement a Magic Dictionary
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the MagicDictionary class:
void buildDict(List<String> dictionary) Initializes the object with the dictionary of words.bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any word in the dictionary, otherwise returns false.class MagicDictionary:
def __init__(self):
self.dictionary = {}
def buildDict(self, dictionary: List[str]) -> None:
self.dictionary = {}
for word in dictionary:
n = len(word)
if n in self.dictionary:
self.dictionary[n].append(word)
else:
self.dictionary[n] = [word]
def search(self, searchWord: str) -> bool:
n = len(searchWord)
if n not in self.dictionary:
return False
for word in self.dictionary[n]:
count_differences = 0
for wc, swc in zip(word, searchWord):
if wc != swc:
count_differences += 1
if count_differences > 1:
break
if count_differences == 1:
return True
return False
True.False.searchWord and (L) is the length of the searchWord.These operations ensure the implementation is efficient while adhering to the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?