class WordDictionary {
private:
vector<WordDictionary*> treeNode; //26个子树
bool isEnd;
public:
WordDictionary() : treeNode(26), isEnd(false){}
//添加单词
void addWord(string word) {
//正常前缀树的添加流程
WordDictionary* node = this;
for(char ch : word){
ch = ch - 'a';
if(node -> treeNode[ch] == nullptr){
node -> treeNode[ch] = new WordDictionary();
}
node = node -> treeNode[ch];
}
node -> isEnd = true;
}
//查找单词
bool search(string word) {
//主要看下面回溯的部分
bool flag = false;
backtrack(word, flag, 0, this);
return flag;
}
void backtrack(string word, bool& flag, int depth, WordDictionary* node){
//有已经找到 与 超过长度 两种情况直接返回
if(flag || depth >= word.size())
return;
char ch = word[depth]; //获取需要查询的字符
int num = ch - 'a'; //获取字符对应的序号
//如果字符是. 或者对应的字符存在
if(ch == '.' || node -> treeNode[num] != nullptr){
//字符是.的情况
if(ch == '.'){
//因为可以替代所有,所以遍历所有可能的节点
for(auto i : node -> treeNode){
//如果不存在则跳过该字符
if(i == nullptr)
continue;
//如果长度匹配上,并且该字符可以是当前字符串的结束点,则返回true
if(depth == word.size() - 1 && i -> isEnd){
flag = true;
return;
}
//快速结束
if(flag)
return;
//查看下一个字符是否匹配
backtrack(word, flag, depth + 1, i);
}
}
//对应字符存在的情况
else{
//如果长度匹配上,且并可以是当前字符串的结束点,则返回true
if(depth == word.size() - 1 && node -> treeNode[num] -> isEnd){
flag = true;
return;
}
//快速结束
if(flag)
return;
//查看下一个字符是否匹配
backtrack(word, flag, depth + 1, node -> treeNode[num]);
}
}
else
return;
}
};
Accepted
29/29 cases passed (1812 ms)
Your runtime beats 5.18 % of cpp submissions
Your memory usage beats 5.09 % of cpp submissions (738.3 MB)