Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Example Input
abc a 123456 45 abc ddd
Example Output
1 4 -1
code:
#include <stdio.h>
#include <string.h>
int next[1000010];
char s1[1000010], s2[1000010];
void getnext()
{
int len = strlen(s2);
int i = 0, j = -1;
next[0] = -1;
while(i<len)
{
if(j==-1||s2[i] == s2[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int kmp()
{
int i = 0, j = 0;
int len1 = strlen(s1), len2 = strlen(s2);
while(i<len1&&j<len2)
{
if(j == -1||s1[i] == s2[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if(j>=len2)
{
return i-j+1;
}
else return -1;
}
int main()
{
while(~scanf("%s", s1))
{
scanf("%s", s2);
getnext();
printf("%d\n", kmp());
}
}
#include <string.h>
int next[1000010];
char s1[1000010], s2[1000010];
void getnext()
{
int len = strlen(s2);
int i = 0, j = -1;
next[0] = -1;
while(i<len)
{
if(j==-1||s2[i] == s2[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int kmp()
{
int i = 0, j = 0;
int len1 = strlen(s1), len2 = strlen(s2);
while(i<len1&&j<len2)
{
if(j == -1||s1[i] == s2[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if(j>=len2)
{
return i-j+1;
}
else return -1;
}
int main()
{
while(~scanf("%s", s1))
{
scanf("%s", s2);
getnext();
printf("%d\n", kmp());
}
}
本文详细介绍了一种高效的字符串匹配算法——KMP算法,并提供了完整的代码实现。通过解析KMP算法的工作原理,包括如何预处理模式串生成next数组以及如何进行模式匹配,帮助读者深入理解并掌握该算法。
8280

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



