加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++实现KMP算法

发布时间:2020-12-16 07:47:02 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #include iostream #include stdlib.h #include vector using namespace std; void NEXT(const string T,vectorint next) { //按模式串生成vector,nex

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考


    #include <iostream>  
    #include <stdlib.h>  
    #include <vector>  
    using namespace std;  
    void NEXT(const string &T,vector<int> &next)  
    {  
        //按模式串生成vector,next(T.size())     
        next[0] = -1;  
        for(int i = 1; i < T.size(); i++)  
        {  
            int j = next[i - 1];  
            while(T[i] != T[j + 1] && j >= 0)  
                j = next[j];  
            //递推计算  
            if(T[i] == T[j + 1])  
                    next[i] = j + 1;  
            else  
                    next[i] = 0;  
        }  
    }  
    string::size_type COUNT_KMP(const string &S,const string &T)  
    {  
        //利用模式串T的next函数求T在主串S中的个数count的KMP算法  
        //其中T非空,  
        vector<int>   next(T.size());  
        NEXT(T,next);  
        string::size_type index,count=0;  
        for(index=0; index < S.size(); ++index)  
        {  
            int pos=0;  
            string::size_type iter = index;  
            while(pos < T.size() && iter<S.size())  
            {     
                if(S[iter] == T[pos])  
                {  
                    ++iter;  
                    ++pos;  
                }  
                else  
                {  
                    if(pos == 0)  
                        ++iter;  
                    else  
                        pos = next[pos - 1] + 1;  
                }  
            }  
            if(pos == T.size() && (iter - index) == T.size())  
                ++count;  
        }  
        return count;  
    }  
    int main()  
    {  
          
        string S,T;  
        cout<<"请输入主串(参照的)"<<endl;  
        cin>>S;  
        cout<<"请输入子串(要查找的)"<<endl;  
        cin>>T;  
        string::size_type count =COUNT_KMP(S,T);  
        cout<<"一共有 "<<count<<" 个子串"<<endl;  
        return 0;  
    }  

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读