#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
void get(char *d,int *next)
{
int i,j;
i=1;j=0;
next[1]=0;
while(i<b)
{
if(j==0||d[i]==d[j])
{
++i;++j;
next[i]=j;
}
else j=next[j];
}
/*for(int q=1;q<=b;q++)
printf("%d$",next[q]);*/
}
int kmp(char *c,char *d)
{
int i=1,j=1;
int next[100];
get(d,next);
while(i<=a&&j<=b)
{
if(j==0||c[i]==d[j])
{
++i;++j;
}
else j=next[j];
}
if(j>b) return i-b;
else return -1;
}
int main()
{
int n;
printf("請輸入測試數據的組數:");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char c[100],d[100];
printf("輸入原字符串長度和欲匹配字符串長度:");
scanf("%d%d",&a,&b);
printf("原字符串:");
for(int i=1;i<=a;i++)
{
scanf("\n%c",&c[i]);
}/*for(int j=1;j<=a;j++)
{
printf("%c+",c[j]);
}*/
printf("欲匹配字符串:");
for(int j=1;j<=b;j++)
{
scanf("\n%c",&d[j]);
} /*for(int j=1;j<=b;j++)
{
printf("%c",d[j]);
}*/
printf("%d\n",kmp(c,d));
}
//cout << "Hello world!" << endl;
return 0;
}
kmp
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.