1.串(string)是由零个或多个字符组成的有限序列
2.子串与主串:串中任意个数的连续字符组成的子序列称为该串的子串。相应的,包含子串的串称为主串。
3.KMP
#include<iostream>
using namespace std;
void nextArray(int *next,string pattern){
next[0]=-1;
int j=0,k=-1;
int len=pattern.length();
while(j<len){
if(k==-1||pattern[j]==pattern[k]){
if(pattern[++j]==pattern[++k])
next[j]=next[k];
else
next[j]=k;
}
else{
k=next[k];
}
}
}
int KMP(string strA, string strB){
int lenA=strA.length();
int lenB=strB.length();
int *next=new int[lenB];
nextArray(next,strB);
int i=0,j=0;
while (i < lenA && j < lenB) {
if (j == -1 || strA[i] == strB[j]) { // 当j为-1时,要移动的是i,当然j也要归0
i++;
j++;
}
else{
j = next[j]; // j回到指定位置
}
}
if (j == lenB) {
return i - j;
}
else{
return -1;
}
}
int main(){
string strA,strB;
cin>>strA>>strB;
cout<<KMP(strA,strB)<<endl;
return 0;
}