https://leetcode.com/problems/add-and-search-word-data-structure-design/description/
写的不够熟练。。。
const int TK = 59, tb = 'A';
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() {
tree.push_back( vector<int>(TK+1, 0) );
}
/** Adds a word into the data structure. */
void addWord(string word) {
int rt = 0, i = 0, nxt;
for ( ; i < word.size(); rt = nxt, i++) {
nxt = tree[rt][ word[i] - tb ];
if (0 == nxt) {
tree[rt][word[i] - tb] = nxt = tree.size();
tree.push_back( vector<int>(TK+1, 0) );
}
}
// cout << "add rt:" << rt << endl;
tree[rt][TK] = 1;
}
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;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
// cout << "-->word:" << word << endl;
return dfs(0, word);
}
bool dfs(int rt, string w) {
// cout << "rt:" << rt << " w:" << w << " t:" << tree[rt][TK] << endl;
if (w.size() == 0) {
return tree[rt][TK];
}
bool ret = false;
if (w[0] != '.') {
if (tree[rt][w[0] - tb ] == 0) return 0;
return dfs(tree[rt][w[0] - tb ], w.substr(1));
} else {
for (char c = 'a'; c <= 'z'; c++) {
if (tree[rt][c - tb ] == 0) continue;
ret |= dfs(tree[rt][c - tb], w.substr(1));
if (ret) return ret;
}
for (char c = 'A'; c <= 'Z'; c++) {
if (tree[rt][c - tb ] == 0) continue;
ret |= dfs(tree[rt][c - tb], w.substr(1));
if (ret) return ret;
}
return ret;
}
}
vector< vector<int> > tree;
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/