Tire 树

终于考完试了,又可以肝算法了

Tire 树是一种数据结构,将字符串用这种数据结构存储起来可以提高匹配的效率

很容易实现查询一个字符串是不是在字典中

具体实现:

class Tire{
public:
    bool isend;
    int cnt;
    Tire* next[26]={NULL};
    Tire(){
        this->isend=false;
        this->cnt=0;
    }
    void insert(string s){
        Tire* cur = this;
        for(int i=s.size()-1;i>=0;i--){
            int t = s[i]-'a';
            if(cur->next[t]==NULL){
                cur->next[t]=new Tire();
            }
            cur=cur->next[t];
        }
        cur->isend=true;
        cur->cnt++;
    }
    bool match(string s){
        Tire* cur = this;
        for(int i=s.size()-1;i>=0;i--){
            if(cur->next[s[i]-'a']==NULL){
                return false;
            }
            cur=cur->next[s[i]-'a'];
        }
        if(cur->isend){
            cout<<cur->cnt<<endl;//这里是统计单词出现的次数
            return true;
        }
        return false;
    }
};

暑假要肝爆啊啊啊!!

posted @ 2020-07-09 10:12  kstranger  阅读(127)  评论(0)    收藏  举报