https://leetcode.com/problems/implement-magic-dictionary/description/
int TK = 26, tb = 'a';
class MagicDictionary {
public:
/** Initialize your data structure here. */
MagicDictionary() {
tree.push_back( vector<int>(TK+1, 0) );
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for (auto w : dict) {
insert(w);
}
}
void insert(string w) {
int rt = 0, nxt, i = 0;
for(; i < w.size() ; rt = nxt, i++) {
nxt = tree[rt][w[i] - tb];
if (0 == nxt) {
tree[rt][w[i]-tb] = nxt = tree.size();
tree.push_back( vector<int>(TK+1, 0) );
}
}
tree[rt][TK] = 1;
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
return dfs(word, 0, 0);
}
bool dfs(string w, int rt, int use) {
if (w.size() == 0) return tree[rt][TK] && use;
bool ret = 0;
int nxt = tree[rt][w[0] - tb];
if (use) {
if (!nxt) return 0;
else return dfs(w.substr(1), nxt, use);
} else {
if (nxt) {
ret |= dfs(w.substr(1), nxt, use);
}
if (ret) return ret;
for (char c = 'a'; c <= 'z'; c++) {
if (c == w[0]) continue;
nxt = tree[rt][ c - tb ];
if (!nxt ) continue;
ret |= dfs(w.substr(1), nxt, 1);
if (ret) return ret;
}
}
return ret;
}
bool sear(string word) {
int rt = 0, i = 0;
for (; rt = tree[rt][ word[i] - tb ]; i++) {
if (i == word.size() - 1) return tree[rt][TK];
}
return 0;
}
vector< vector<int> > tree;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* bool param_2 = obj.search(word);
*/
http://www.cnblogs.com/grandyang/p/7612918.html
这里讲了一种更好写的写法,枚举现在这个字符串所有可能组合,然后看字典里面是不是 有
class MagicDictionary {
public:
/** Initialize your data structure here. */
MagicDictionary() {}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for (string word : dict) s.insert(word);
}
/** 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 t = word[i];
for (char c = 'a'; c <= 'z'; ++c) {
if (c == t) continue;
word[i] = c;
if (s.count(word)) return true;
}
word[i] = t;
}
return false;
}
private:
unordered_set<string> s;
};