KMP求法(通过next)

这是一个使用C++实现KMP算法的示例,通过计算next数组来寻找模式串在主串中的匹配位置。程序首先定义了求next数组的函数`get_next`,然后实现了KMP匹配的`Index_KMP`函数,最后在`main`函数中获取用户输入的主串、子串和起始位置,输出匹配结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 用next求kmp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

void get_next(char T[],int next[]){
 //求模式串T的next函数值并存入数组next
 int i=1;next[1]=0;
 int j=0;
 int n;
 n=strlen(T);
 while(i<n){
  if(j==0 || T[i]==T[j]) {++i;++j;next[i]=j;}
  else j=next[j];
 }
}


int Index_KMP(char S[],char T[],int pos,int next[]){
 //利用模式串T的next函数求T在主串中第pos个字符之后的位置的
 //KMP算法.其中,T非空,1<=pos<=StrLength(S).
 int i=pos;
 int j=1;
 int m,n;
 m=strlen(S);
 n=strlen(T);
 while(i<=m && j<=n){
  if(j==0 || S[i]==T[j]){++i;++j;}//继续比较后续字符
  else j=next[j];
 }
 if(j>n) return i-n;//匹配成功
 else return 0;
}

int main(int argc, char* argv[])
{
 char CS[100],char CT[100];
 int data,data1,ne[100];
 cout<<"请输入主串"<<endl;
 cin>>CS;
 cout<<"请输入子串"<<endl;
 cin>>CT;
 cout<<"请输入主串中从第pos个字符开始匹配的"<<endl;
 cin>>data;
 get_next(CT,ne);
 data1=Index_KMP(CS,CT,data,ne);
 cout<<data1<<endl;

 return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值