leetCode211(字典树)

今天刷到一个题,要我们设计一个数据结构能够快速匹配字符串的数据结构。也就是大名鼎鼎的字典树。也可以叫做前缀匹配树。像路由器对分组的ip与路由表项匹配的时候用的数据结构就是这个。
还是蛮重要的,故提笔记之


下面请看题

在这里插入图片描述
思路:像这个题,我们需要设计的字典树的度为26(因为有26个字母)。树上每个节点到根的路径是唯一的,故都可以代表一个字符串。因为有的时候我们插入的字符串可能是已经插入的字符串的子串,所以我们需要在每个节点里面设置一个布尔字段is_end.表示是否有以当前节点结尾的字符串。这样我们每次插入字符串时,从字符串第一个字符一个一个的插入,在插入的过程中可以创建新的节点,因为存在’.'可以匹配任意字符,所以我们可以设置递归插入会更省事点,要不然我们就得在某一次迭代里面插入26次了。不好组织代码。
废话说了那麽多,还是先贴上代码把

class WordDictionary {
private:
    struct node{
        vector<node *> arr;
        bool is_end;
        node(){
            arr.resize(26,nullptr);
            is_end = false;
        }
    };
    node *head;
protected:
    void insert(node *cur, int s, string &word){
        if(s==word.size()){
            cur->is_end=true;
            return ;
        }
        if(word[s]=='.'){
            for(int i=0;i<26;i++){
                if(cur->arr[i]==nullptr){
                    cur->arr[i]=new node;
                }
                insert(cur->arr[i],s+1,word);     
            }
        }else{
            if(cur->arr[word[s]-'a']==nullptr){
                cur->arr[word[s]-'a'] = new node;
            }
            insert(cur->arr[word[s]-'a'], s+1, word);
        }
    }
    bool comp(node *cur, string &word, int s){
        if(cur==nullptr){
            return false;
        }
        if(s==word.size()){
            return cur->is_end;
        }
        char c= word[s];
        if(c=='.'){
            bool flag = false;
            for(int i=0;i<26;i++){
                flag=flag||comp(cur->arr[i],word, s+1);
            }
            return flag;
        }else{
            return comp(cur->arr[c-'a'], word, s+1);
        }
    }
public:
    WordDictionary() {
        head = new node;
    }
    
    void addWord(string word) {
        insert(head, 0, word);
    }
    
    bool search(string word) {
        return comp(head, word, 0);
      
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值