211. 添加与搜索单词——前缀数2.0、回溯

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值