KMP算法查找串S中含串P的个数count

#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;
            }   
        }//while end
        if(pos==T.size()&&(iter-index)==T.size())++count;
    } //for end
    return count;
}
int main(int argc, char *argv[])
{
    string S="abaabcacabaabcacabaabcacabaabcacabaabcac";
    string T="ab";
    string::size_type count=COUNT_KMP(S,T);
    cout<<count<<endl;
 
  system("PAUSE"); 
  return 0;
}

KMP(Knuth-Pratt)算法是一种用于查找字符中特定子出现次数的经典技术,特别是在处理大量数据时,其效率相对较高。在C++中,我们可以使用该算法来计算两个字符之间的匹配位置,进而推断出相同子的数量。 KMP算法的核心在于构建一个失配指针数组,这个数组可以帮助我们在搜索过程中跳过不必要的比较,提高匹配速度。以下是步骤概览: 1. **创建部分匹配表(Partial Match Table, PMT)**:根据模式字符计算失配指针。PMT[i]表示如果模式的第一个i+1位与主匹配失败,则应该跳转到模式的多少位置继续尝试。 2. **匹配过程**:对于主中的每个字符,与模式进行逐个比较。如果匹配,继续移动;如果不匹配,查看PMT找到适当的跳转位置。 3. **计数相同子**:每当遇到完整的匹配(包括原模式和非空的前缀),就增加计数器,并继续从下一个位置开始新一轮的匹配。 C++实现KMP算法并计算相同子数量的一个基本版本可能会这样设计: ```cpp #include <vector> #include <string> std::vector<int> getPMTable(const std::string &pattern) { int n = pattern.size(); std::vector<int> pm(n); for (int i = 1, j = -1; i < n; ++i) { while (j != -1 && pattern[i] != pattern[j + 1]) { j = pm[j]; } if (pattern[i] == pattern[j + 1]) { ++j; } pm[i] = j; } return pm; } int countSubstrings(std::string text, const std::string &pattern) { int m = pattern.length(); std::vector<int> pm = getPMTable(pattern); int count = 0; int i = 0, j = 0; while (i < text.length()) { if (text[i] == pattern[j]) { i++; j++; } else if (j != 0) { j = pm[j - 1]; } else { i++; } if (j == m) { // 完整匹配 count++; j = pm[j - 1]; // 跳回下一个位置 } } return count; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值