2022.10.16数据结构实现KMP字符串匹配
任务描述
本关的编程任务是补全 step2/kmp.cpp 文件中的KmpGenNext函数,以实现 KMP 字符串匹配。该函数生成给定字符串的next数组。
编程要求
本关的编程任务是补全 step2/kmp.cpp 文件中的KmpGenNext函数,以实现 KMP 字符串匹配。该函数生成给定字符串的next数组,生成算法请你查阅相关资料。
评测说明
本关的测试文件是 step2/Main.cpp ,测试过程如下:
平台编译 step2/Main.cpp ,然后链接相关程序库并生成 exe 可执行文件;
平台运行该 exe 可执行文件,并以标准输入方式提供测试输入;
平台获取该 exe 可执行文件的输出,然后将其与预期输出对比,如果一致则测试通过;否则测试失败。
输入输出格式:
输入格式:
第一行输入母串
第二行输入子串
输出格式:
输出Location: #,其中#是子串在母串中的位置编号
以下是平台对 step2/Main.cpp 的样例测试集:
样例输入:
stringabcedf1stringabcdef2stringabcdef3stringabcdef4stringabcdef5stringabcdef6stringabcdef7
stringabcdef7
样例输出:
Location: 78
开始你的任务吧,祝你成功!
C++代码
/*************************************************************
date:
copyright: Zhu En
DO NOT distribute this code without my permission.
**************************************************************/
//字符串 实现文件
//
#include <stdio.h>
#include <stdlib.h>
#include "kmp.h"
/
void KmpGenNext(char* p, int* next)
//生成p的next数组, next数组长度大于等于字符串p的长度加1
{
// 请在此添加代码,补全函数KmpGenNext
/********** Begin *********/
next[0]=-1;
int k= -1;
for(int i=1;p[i-1]!=0;i++)
{
while(k>=0&&p[k]!=p[i-1])
{
k=next[k];
k=k+1;
if (p[i]==p[k])
{
next[i]=next[k];
}
else
{
next[i]=k;
}
}
}
/********** End *********/
}
int KmpFindSubWithNext(char* t, char* p, int* next)
//从t中查找子串p的第一次出现的位置
//若找到,返回出现的位置,否则返回-1
{
int i=0, j=0;
while(p[i]!=0 && t[j]!=0) {
if(p[i]==t[j]) {
i++;
j++;
}
else if (next[i]>=0) {
i = next[i];
}
else {
i=0;
j++;
}
}
if(p[i]==0) return j-i; //found
else return -1; //not found
}