KMP算法(C++版)

有关字符串匹配的最有效的算法。

其算法复杂度为两个字符串的长度之和(m+n)。

与C语言版本想比,这个版本只是使用C++语法,功能还是被封装在函数中。

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <vector>

using namespace std;

inline 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;
    }
}

inline 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;
            }
        }//whileend
        if(pos==T.size() && (iter-index)==T.size())
            ++count;
    }//forend
    return count;
}

int main(void)
{
    string S="abaabcacabaabcacabaabcacabaabcacabaabcac";
    string T="ab";
    string::size_type count=COUNT_KMP(S,T);
    cout << count << endl;
    return 0;
}


转载于:https://www.cnblogs.com/tigerisland/p/7564922.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值