题目来源
题目描述
题目解析
这道题是leetcode:208. Implement Trie (Prefix Tree) 实现字典树(前缀树)的衍生,唯一不同的是search需要重写一下,因为这道题里面.
可以代替任意字符,所以一旦有了.
,就要查找所有的子树,只要有一个返回true,整个search就返回true
class WordDictionary {
class TrieNode {
public:
TrieNode () : children(26, nullptr), is_word(false){
}
~TrieNode (){
for(auto it : children){
delete it;
}
}
std::vector<TrieNode *> children;
bool is_word;
};
public:
WordDictionary() {
root = new TrieNode();
}
~WordDictionary(){
delete root;
}
void addWord(string word) {
TrieNode *p = root;
for(auto &a : word){
int i = a - 'a';
if(p->children[i] == NULL){
p->children[i] = new TrieNode();
}
p = p->children[i];
}
p->is_word = true;
}
bool search(string word) {
return dfs(word, root, 0);
}
bool dfs(const string & word, TrieNode *p, int index){
if(index == word.size()){
return p->is_word;
}
if(word[index] == '.'){
for(auto &it : p->children){
if(it && dfs(word, it, index + 1)){
return true;
}
}
return false;
}else{
return p->children[word[index] - 'a'] &&
dfs(word, p->children[word[index] - 'a'], index + 1);
}
}
private:
TrieNode *root;
};