中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

C++實現(xiàn)KMP算法

2018-07-20    來源:open-open

容器云強勢上線!快速搭建集群,上萬Linux鏡像隨意使用

    #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函數(shù)求T在主串S中的個數(shù)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;  
    }  

標(biāo)簽:

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:一個更改 hosts 的 PHP 腳本

下一篇: jdbc 使用PreparedStatement來存儲和讀取大數(shù)據(jù)(Blob或Clob)