给两个字符串A、B, 从A中找出第一次出现B的位置。
输入格式:
第一行输入一个整数n,表示测试数据的个数
对于每组测试数据,输入两个字符串S T,S和T中间用一个空格隔开,每组数据占一行。
输出格式:
对于每组测试数据,输出A中找出第一次出现B的位置,如果A不包含B,输出“not find!”
输入样例:
3
abcdabbcd abbc
abcd efg
abbcdd bbc
输出样例:
4
not find!
1
代码如下:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void getNext(const string& pattern,vector<int>& next)
{
int j=-1;
next[0]=j;
for(int i=1;i<pattern.size();i++)
{
while(j>=0&&pattern[i]!=pattern[j+1])
{
j=next[j];
}
if(pattern[i]==pattern[j+1])
{
j++;
}
next[i]=j;
}
}
int kmp(const string& text,const string& pattern)
{
vector<int> next(pattern.size());
getNext(pattern, next);
int j =-1;
for(int i=0;i<text.size();i++)
{
while(j>=0&&text[i]!=pattern[j+1])
{
j=next[j];
}
if(text[i]==pattern[j+1])
{
j++;
}
if(j==(int)pattern.size()-1)
{
return i-pattern.size()+1;
}
}
return -1;
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
string text,pattern;
cin>>text>>pattern;
int pos=kmp(text,pattern);
if(pos!=-1)
{
cout<<pos<<endl;
}else{
cout<<"not find!"<<endl;
}
}
return 0;
}