定长顺序存储表示字符串,用KMP算法找出模式串
串S = ‘aafhjkxdeeshtksslshtvdfdhshtksslshtbfdmhgshtksslshtsfesrgb’
用定长顺序存储表示字符串,用KMP算法找出模式串T=‘shtksslsht’出现在主串S(执行添加和删除操作之前的S)中的所有位置(不止一个),并打印输出。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#define maxlen 255
typedef char sstring[maxlen + 1];
int InitStr(sstring s)
{
s[0] = 0;
return 1;
}
int strLength(sstring s)
{
return s[0];
}
int strAssign(sstring s, sstring c)
{
int i;
for (i = 0; c[i] != '\0' && i + 1 < maxlen; i++)
{
s[i + 1] = c[i];
}
s[i + 1] = '\0';
s[0] = i;
return 1;
}
void clears(sstring s)
{
s[0] = 0;
}
int strEmpty(sstring s)
{
if (s[0] == 0)
return 1;
else
return 0;
}
void Next(sstring T, int *next)
{
int i = 1;
next[1] = 0;
int j = 0;
while (i < strlen(T))
{
if (j == 0 || T[i - 1] == T[j - 1])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int Index_KMP(sstring S, sstring T, int pos)
{
int next[10];
Next(T, next); //根据模式串T,初始化next数组
int i = pos;
int j = 1;
while (i <= strlen(S) && j <= strlen(T))
{
//j==0:代表模式串的第一个字符就和当前测试的字符不相等;S[i-1]==T[j-1],如果对应位置字符相等,两种情况下,指向当前测试的两个指针下标i和j都向后移
if (j == 0 || S[i - 1] == T[j - 1])
{
i++;
j++;
}
else
{
j = next[j]; //如果测试的两个字符不相等,i不动,j变为当前测试字符串的next值
}
}
if (j > strlen(T))
{ //如果条件为真,说明匹配成功
return i - (int)strlen(T);
}
return 0;
}
int main()
{
sstring s, in;
InitStr(s);
InitStr(in);
strAssign(s, "aafhjkxdeeshtksslshtvdfdhshtksslshtbfdmhgshtksslshtsfesrgb");
strAssign(in, "shtksslsht");
int i;
while (i = Index_KMP(s + 1, in + 1, i))
{
printf("%d ", i);
i++;
}
return 0;
}