LeetCode Solutions
676. Implement Magic Dictionary
Time: Constructor: $O(1)$, buildDict(dictionary: List[str]): $O(\Sigma |\texttt{dictionary[i]}|^2)$ search(searchWord: str): $O(|\texttt{searchWord}|^2)$ Space: $O(\Sigma |\texttt{dictionary[i]}|)$
class MagicDictionary {
public:
void buildDict(vector<string> dictionary) {
for (const string& word : dictionary)
for (int i = 0; i < word.length(); ++i) {
const string replaced = getReplaced(word, i);
dict[replaced] = dict.count(replaced) ? '*' : word[i];
}
}
bool search(string searchWord) {
for (int i = 0; i < searchWord.length(); ++i) {
const string replaced = getReplaced(searchWord, i);
if (dict.count(replaced) && dict[replaced] != searchWord[i])
return true;
}
return false;
}
private:
unordered_map<string, char> dict;
string getReplaced(const string& s, int i) {
return s.substr(0, i) + '*' + s.substr(i + 1);
}
};
class MagicDictionary {
public void buildDict(String[] dictionary) {
for (final String word : dictionary)
for (int i = 0; i < word.length(); ++i) {
final String replaced = getReplaced(word, i);
dict.put(replaced, dict.containsKey(replaced) ? '*' : word.charAt(i));
}
}
public boolean search(String searchWord) {
for (int i = 0; i < searchWord.length(); ++i) {
final String replaced = getReplaced(searchWord, i);
if (dict.getOrDefault(replaced, searchWord.charAt(i)) != searchWord.charAt(i))
return true;
}
return false;
}
private Map<String, Character> dict = new HashMap<>();
private String getReplaced(final String s, int i) {
return s.substring(0, i) + '*' + s.substring(i + 1);
}
}
class MagicDictionary:
def __init__(self):
self.dict = {}
def buildDict(self, dictionary: List[str]) -> None:
for word in dictionary:
for i, c in enumerate(word):
replaced = self._getReplaced(word, i)
self.dict[replaced] = '*' if replaced in self.dict else c
def search(self, searchWord: str) -> bool:
for i, c in enumerate(searchWord):
replaced = self._getReplaced(searchWord, i)
if self.dict.get(replaced, c) != c:
return True
return False
def _getReplaced(self, s: str, i: int) -> str:
return s[:i] + '*' + s[i + 1:]