#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
#define bool char
#define true 1
#define false 0
//定义串
typedef struct SString
{
char ch[MAXSIZE];
int len;
}SString;
////找到主串中与子串相同的值
//bool Index(SString *s, SString *t, int pos)
//{
// int i = pos, j = 1;
// while (i <= s->len && j <= t->len)
// {
// if (s->ch[i] == t->ch[j])
// {
// i++;
// j++;
// }
// else
// {
// i = i - j + 2;
// j = 1;
// }
// }
// if (j > t->len)
// return i - t->len;
// else
// return 0;
//}
//求模式串t的next函数值并存入数组next
//第一个参数表示模式串t的指针,
//第二个参数表示存储next数组的指针,
//第三个参数表示模式串t的长度
void GetNext(SString* t,int*next)
{
int i = 1, j = 0;
next[1] = 0;
while (i < t->len)
{
if (j == 0 || t->ch[i] == t->ch[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
//利用模式串t的next函数求t在主串s中第pos个字符之后的位置
int IndexKMP(SString* s, SString* t, int pos,int *next)
{
int i = pos, j = 1;
while (i <= s->len && j <= t->len)
{
if (j == 0 || s->ch[i] == t->ch[j]) //继续比较后续字符
{
++i;
++j;
}
else //模式串向后移动
j = next[j];
}
if (j > t->len) //匹配成功,返回匹配起始位置
return i - t->len;
else
return 0;
}
int main()
{
int locate;
int next[MAXSIZE];
SString s, t;
printf("主串:");
scanf_s("%s", s.ch,MAXSIZE);
printf("子串:");
scanf_s("%s", t.ch,MAXSIZE);
GetNext(&t,&next);//参数为指针类型,故应该传递&t,而不是t
locate=IndexKMP(&s,&t,0,&next);//参数为指针类型
printf("匹配位置:%d", locate);
}
程序的输出结果为:
请问怎么改,才能得到正确的结果啊QAQ