Implement Magic Dictionary
Thoughts
Code
class MagicDictionary {
Map<String, Map<Integer, Set<String>>> map;
/** Initialize your data structure here. */
public MagicDictionary() {
map = new HashMap<>();
}
/** Build a dictionary through a list of words */
public void buildDict(String[] dict) {
for (String str : dict) {
for (int i = 0; i < str.length(); i++) {
StringBuilder sb = new StringBuilder(str);
String sub = sb.deleteCharAt(i).toString();
if (!map.containsKey(sub)) {
map.put(sub, new HashMap<>());
}
if (!map.get(sub).containsKey(i)) {
map.get(sub).put(i, new HashSet<>());
}
map.get(sub).get(i).add(str);
}
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
public boolean search(String word) {
for (int i = 0; i < word.length(); i++) {
StringBuilder sb = new StringBuilder(word);
String sub = sb.deleteCharAt(i).toString();
if (map.containsKey(sub) && map.get(sub).containsKey(i)) {
if (!map.get(sub).get(i).contains(word) || map.get(sub).get(i).size() > 1) {
return true;
}
}
}
return false;
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* boolean param_2 = obj.search(word);
*/Analysis
Last updated