KMP算法实现

本文提供了一个基于KMP算法的字符串匹配实现,包括计算next数组和next_val数组的函数,并通过测试用例验证了其正确性。

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

依照KMP实现的算法,附带测试用例。

#include <algorithm>
#include
<iostream>
#include
<iterator>
#include
<string>
#include
<vector>
#include
<cassert>
#include
<cstring>
using namespace std;


/**计算next***/
void kmp_next(char *pattern,int *next)
{
int i = 0 ;
int j = next[0] = -1;
while(pattern[i]!= '\0')
{
if((j == -1) || (pattern[i] == pattern[j]))
next[
++i]= ++j;
else
j
= next[j];
}
}
/**计算next_val***/
void kmp_next_val(char *pattern,int *next_val)
{
int i = 0;
int j = next_val[0] = -1;
while(pattern[i]!='\0')
{
if((j == -1)|| (pattern[i] == pattern[j]))
if(pattern[++i] != pattern[++j])
next_val[i]
= j;
else
next_val[i]
= next_val[j];
else
j
= next_val[j];
}
}
/****match 是长串**

*****pattern 是模式串*
*/
int kmp_match(char *match,char *pattern)
{
int m = strlen(pattern);

int next[m];
int i,j;
/**打印表格**/
for(i = 0; i < m ; ++i)
cout
<<i<<'\t';
cout
<<endl;
kmp_next(pattern,next);
copy(next,next
+m,ostream_iterator<int > (cout,"\t"));
cout
<<endl;
kmp_next_val(pattern,next);
copy(next,next
+m,ostream_iterator<int > (cout,"\t"));
cout
<<endl;

i
= j = 0;
while((match[i]!='\0')&&(pattern[j]!='\0'))
{
if((j == -1)||(match[i] == pattern[j]))
++i,++j;
else
j
= next[j];

}
return j == m?(i -j):-1;
}


int main(int argc,char *argv[])
{
char src[max_size];
char dst[max_size];
int m ,n;
int position = 0;
while(cin >> src >> dst)
{
position
= kmp_match(src,dst);

if(position != -1)
cout
<<"find at \t "<<position<<endl;
else
cout
<<"not a substring\n";

cout
<<"--------end----------\n\n";
}
return 0;
}

转载于:https://www.cnblogs.com/westfly/archive/2011/05/04/kmp_algorithm.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值