数据结构实验之串一:KMP简单应用
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
给定两个字符串string1和string2,判断string2是否为string1的子串。
输入
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
输出
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
示例输入
abc a 123456 45 abc ddd
示例输出
1 4 -1
提示
来源
cjx
示例程序
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int next[1000002];//定义为全局变量
void Get_next(char s[])
{
int len=strlen(s);//调用函数求字符数组长度
int i=0;
int j=-1;
next[0]=-1;
while (i<len)
{
if(j==-1||s[i]==s[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}
}
void kmp(char s1[],char s2[])
{
int len1=strlen(s1);//调用函数求字符数组长度
int len2=strlen(s2);//调用函数求字符数组长度
int i=0,j=0;
while(i<len1&&j<len2)
{
if(j==-1||s1[i]==s2[j])
{
++i;
++j;
}
else
{
j=next[j];//j回溯到next[j]的位置
}
}
if(j==len2)//存在子串
printf("%d\n" ,i-len2+1);
else
printf("-1\n");
}
int main()
{
char st1[1000002],st2[1000002];
while(~scanf("%s",st1))//多组输入
{
cin>>st2;
Get_next(st2);
kmp(st1,st2);
}
}
768

被折叠的 条评论
为什么被折叠?



