676. Implement Magic Dictionary¶
Difficulty: Medium
LeetCode Problem View on GitHub
676. Implement Magic Dictionary
Medium
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:
MagicDictionary()Initializes the object.void buildDict(String[] dictionary)Sets the data structure with an array of distinct stringsdictionary.bool search(String searchWord)Returnstrueif you can change exactly one character insearchWordto match any string in the data structure, otherwise returnsfalse.
Example 1:
Input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
Output
[null, null, false, true, false, false]
Explanation
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
Constraints:
1 <= dictionary.length <= 1001 <= dictionary[i].length <= 100dictionary[i]consists of only lower-case English letters.- All the strings in
dictionaryare distinct. 1 <= searchWord.length <= 100searchWordconsists of only lower-case English letters.buildDictwill be called only once beforesearch.- At most
100calls will be made tosearch.
Solution¶
import java.util.ArrayList;
class MagicDictionary {
private ArrayList<String> res;
public MagicDictionary() {
res = new ArrayList<>();
}
public void buildDict(String[] dictionary) {
for (String word : dictionary)
res.add(word);
}
public boolean search(String searchWord) {
for (String word : res) {
if (ok(word, searchWord))
return true;
}
return false;
}
private boolean ok(String word, String searchWord) {
int n = word.length();
int m = searchWord.length();
if (n != m)
return false;
int count = 0;
for (int i = 0; i < n; i++) {
if (word.charAt(i) != searchWord.charAt(i))
count++;
}
return count == 1;
}
}
/**
Your MagicDictionary object will be instantiated and called as such:
MagicDictionary obj = new MagicDictionary();
obj.buildDict(dictionary);
boolean param_2 = obj.search(searchWord);
*/
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here