题目

KMP解法
#include<bits/stdc++.h>
using namespace std;
char s[1000010],q[100010];
int ne[100010];
int n;
int main()
{
cin>>s+1>>n;
while(n--){
cin>>q + 1;
ne[1] = -1;
for(int i = 2 , j = 0 ; q[i] != '\0' ; i ++){
while(j && q[j + 1] != q[i]) j = ne[j];
if(q[j + 1] == q[i]) j ++;
ne[i] = j;
}
int ans = -1;
for(int i = 1 , j = 0; s[i] != '\0' ; i ++){
while(j && q[j + 1] != s[i]) j = ne[j];
if(q[j + 1] == s[i]) j ++;
if(q[j + 1] == '\0'){
ans = i - j ;
break;
}
}
if(ans == -1) cout<<"Not Found";
else{
cout<<s+ans+1;
}
if(n) cout<<endl;
}
return 0;
}
strstr解法:
#include<iostream>
#include<string.h>
using namespace std;
const int N = 1e6 + 10;
char s[N],q[N];
int n;
int main()
{
cin>>s>>n;
while(n--){
cin>>q;
if(strstr(s,q) != NULL) cout<<strstr(s,q)<<endl;
else cout<<"Not Found"<<endl;
}
}