数据结构实验之串一: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
提示
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int l1, l2;
int next[1000100]; //next数组
char s[1000010], t[1000010]; //母串和子串
void get_next(char t[], int next[]) //next数组求解函数
{
int i=1; //初始化
next[1] = 0;
int j = 0;
while(i < l2) //循环次数 子串的长度
{
if(j == 0 || t[i] == t[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
void KMP(int n, int m)
{
//利用模式串(子串)的next函数求在主串
//中第pos个字符之后的位置 1<=pos<=strlen(s);
int pos=1;
int k = 1;
while(pos <= n&&k <= m)
{
if(k == 0 || s[pos] == t[k]) //继续比较后续字符
{
++pos;
++k;
}
else
{
k = next[k]; //模式串向右移动
}
}
if(k > m) //匹配成功
printf("%d\n", pos-m);
else
printf("-1\n");
}
int main()
{
while(~scanf("%s", s))
{
scanf("%s", t);
l1 = strlen(s);
l2 = strlen(t);
get_next(t, next);
KMP(l1-1, l2-1);
}
return 0;
}