#include "stdio.h"
#include "stdlib.h"
#include<iostream>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASLBLE -1
#define OVERFLOW -2
#define MAXSTRLEN 255 //用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN + 1]; //0号单元存放串的长度
void get_next(SString T, int next[]) {
// 算法4.7
// 求模式串T的next函数值并存入数组next
// 请补全代码
next[1] = 0;
int i = 1, j = 0;
while (i < T[0]) {
if (j == 0 || T[i] == T[j]) {
next[++i] = ++j;
}
else
j = next[j];
}
}
int Index_KMP(SString S, SString T, int pos) {
// 算法4.6
// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置
// KMP算法。请补全代码
int i = 1, j = 1;
int next[20];
get_next(T, next);
pos = T[0];
while (S[0] - i >= T[0] - j) {//主串长度大于或等于模式串剩余个数
if (++j == 1 && S[i] != T[j]) {
i++;
}
if (S[i] == T[j]) {
i++;
j++;
}
else {
j = next[j];
}
if (j - T[0] == 1) {
return pos=i-T[0];
}
}
return 0;
}
int main()
{
SString T, S;
int i, j, n;
char ch;
int pos=0;
scanf("%d", &n); // 指定n对需进行模式匹配的字符串
ch = getchar();
for (j = 1; j <= n; j++)
{
ch = getchar();
for (i = 1; i <= MAXSTRLEN && (ch != '\n'); i++) // 录入主串
{
S[i] = ch;
ch = getchar();
}
S[0] = i - 1; // S[0]用于存储主串中字符个数
ch = getchar();
for (i = 1; i <= MAXSTRLEN && (ch != '\n'); i++) // 录入模式串
{
T[i] = ch;
ch = getchar();
}
T[0] = i - 1; // T[0]用于存储模式串中字符个数
pos=Index_KMP(S,T,pos); // 请填空
printf("%d\n", pos);
}
return 0;
}
SCAU-8592-数据结构- KMP算法
于 2022-04-23 10:09:30 首次发布