题目描述:
给定两个由小写字母构成的字符串 L 和 S 。
请你从左到右,找出子串 L 在母串 S 中每次出现的开始位置(匹配位置)。
输入格式:
第一行:给一个全由小写字母构成的母串 S(0<S的长度≤1000000);
第二行:给一个全由小写字母构成的子串 L(0<L的长度≤S的长度)。
输出格式:
按升序输出一行一个整数,分别表示子串 L 在母串 S 中每次出现的开始位置。
如果子串 L 在母串 S 中没有出现,则输出“NO”。
样例输入1:
yuabcierabcde
abc
样例输出1:
3
9
样例输入2:
abcdefg
abcdefu
样例输出2::
NO
题目分析:
KMP模板题。
附代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<cctype>
#include<queue>
#include<iomanip>
#include<set>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
char s[maxn],t[maxn];
int lens,lent,nxt[maxn];
bool check;
int main()
{
//freopen("lx.in","r",stdin);
scanf("%s%s",s+1,t+1);
lens=strlen(s+1);lent=strlen(t+1);
for(int i=2,j=0;i<=lent;i++)
{
while(j!=0&&t[i]!=t[j+1]) j=nxt[j];
if(t[i]==t[j+1]) j++;
nxt[i]=j;
}
for(int i=1,j=0;i<=lens;i++)
{
while(j!=0&&s[i]!=t[j+1]) j=nxt[j];
if(s[i]==t[j+1]) j++;
if(j==lent)
{
printf("%d\n",i-lent+1);
j=nxt[lent];
check=true;
}
}
if(check==false) printf("NO");
return 0;
}