解法一:unordered_map<int, vector<string>>
change one character to a word in the dictionary (same length)
class MagicDictionary {
public:
/** Initialize your data structure here. */
MagicDictionary() {
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for(string w: dict){
m[w.size()].push_back(w);
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
for(string w: m[word.size()]){
int cnt=0, i=0;
for(;i<word.size();i++){
if(w[i]!=word[i]) cnt++;
if(cnt==2) break;
}
if(cnt==1) return true;
}
return false;
}
private:
unordered_map<int, vector<string>> m;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dict);
* bool param_2 = obj->search(word);
*/
解法二:unordered_set<string>
class MagicDictionary {
public:
/** Initialize your data structure here. */
MagicDictionary() {
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for(string w: dict){
s.insert(w);
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
for(int i=0;i<word.size();i++){
char cur = word[i];
for(char c='a'; c<='z';c++){
if(c==cur) continue;
word[i] = c;
if(s.count(word)) return true;
}
word[i] = cur;
}
return false;
}
private:
unordered_set<string> s;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dict);
* bool param_2 = obj->search(word);
*/