在这里插入代码片
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* 2016年下半年下午试题 /
/
模式匹配是指给定主串t和子串s,在主串t中寻找子串s过程,其中s称为模式。
如果匹配成功,返回 s在t中的位置,否则返回 -1
KMP算法 用next 数据对匹配过程进行了优化。KMP算法如下。
(1)在串t和串s中,分别设比较下标i=j=0.
(2) 如果串t和串s都还有字符,则循环执行下列操作
*1. 如果j=-1;或者t[i]==s[j],则将i和j分别加1,继续比较t和s的下一个字符
*2.否则,将j向左滑动到next[j] 的位置,即j=next[j]
(3) 如果s中所有字符已比较完毕,则返匹配的起始位置(从1开始);否则返回-1.
其中,next数组根据子串s求解。求解next数组的代码已由get_next函数给出。
*/
/*
(1) 常量和变量说明如下.
t,s:长度为Is的字符串。
next:数组,长度为IS
*/
/* 求next[]的值*/
void get_next(int* next, char* s, int Is)
{
int i = 0, j = -1;
next[0] = -1;/*初始化next[0] */
while (i < Is)
{
/还有字符/
if (j == -1 || s[i] == s[j])
{
/匹配/
j++;
i++;
printf(“i=%d,j=%d \n”, i, j);
if (s[i] == s[j])
next[i] = next[j];
else
next[i] = j;
}
else
j = next[j];
}
}
int kmp(int* next, char* t, char* s, int lt, int ls)
{
int i = 0, j = 0;
while (i < lt && j < ls) //原题第一空 处
{
if (j == -1 || t[i] == s[j]) //原题第二空 处
{
i++;
j++;
}
else
{
j = next[j];//原题第三空 处
}
}
if (j >= ls)
return i - ls + 1; //原题第四空 处
else
return -1;
}
int main(int argc, char* argv[]) {
char* t = "AABBCBBABBABBCAC";
char* s = "BBABBCAC";
int next[8];
get_next(next, s, 8);
int i;
for (i = 0;i < 8;i++)
{
printf("%d ", next[i]);
}
printf("\n %d", kmp(next, t, s, 16, 8));
return 0;
}