https://leetcode.com/problems/implement-magic-dictionary/description/
class MagicDictionary {
unordered_map<string,vector<pair<int,char>>> d;
public:
/** Initialize your data structure here. */
MagicDictionary() {
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for(string s : dict) {
for(int i=0; i<s.size(); i++) {
string w = s.substr(0, i) + s.substr(i+1);
d[w].push_back({i, s[i]});
}
}
}
/** 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++) {
string w = word.substr(0, i) + word.substr(i+1);
if(d.count(w)) {
for(auto& p : d[w]) {
if(p.first == i && p.second != word[i]) return true;
}
}
}
return false;
}
};
or,
class MagicDictionary {
unordered_map<string, vector<string>> d;
public:
/** Initialize your data structure here. */
MagicDictionary() {
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for(string s : dict) {
for(int i=0; i<s.size(); i++) {
string w = s.substr(0, i) + s.substr(i+1);
d[w].push_back(s);
}
}
}
/** 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++) {
string w = word.substr(0, i) + word.substr(i+1);
if(d.count(w)) {
for(string& s: d[w]) {
if(s.size() == word.size()) {
int cnt = 0;
for(int i=0; i<s.size(); i++) {
if(word[i] != s[i]) cnt++;
if(cnt==2) break;
}
if(cnt==1) return true;
}
}
}
}
return false;
}
};
No comments:
Post a Comment