1、BF算法,查找子串
#include<bits/stdc++.h>
using namespace std;
int fd(string s1,string s2)
{
int i=0,j=0;
while(i<s1.size()&&j<s2.size())
{
if(s1[i]==s2[j]) i++,j++;
else i=i-j+1,j=0; //重点是i-j+1,原来位置+1
}
if(j>=s2.size()) return i-s2.size();
else return -1;
}
int main(void)
{
string s1,s2;
cin>>s1>>s2;
cout<<fd(s1,s2);
return 0;
}
复杂度O(n*m)
2、kmp算法
待查找串:str;
标准串:ptr;
重点:查找ptr中的前缀子串和后缀子串相同的数量。
参考文章:https://blog.csdn.net/starstar1992/article/details/54913261/
#include<bits/stdc++.h>
using namespace std;
void Next(char* str,int *next,int len)
{
int k=-1;
next[0]=-1;
for(int q=1;q<=len-1;q++)
{
while(k>-1&&str[k+1]!=str[q])
{
k=next[k];
}
if(str[k+1]==str[q]) k=k+1;
next[q]=k;
}
}
int KMP(char* str,int sl,char* ptr,int pl)
{
int k=-1;
int *next=new int[120];
Next(ptr,next,pl);
for(int i=0;i<sl;i++)
{
while(k>-1&&ptr[k+1]!=str[i])
{
k=next[k];
}
if(ptr[k+1]==str[i]) k++;
if(k==pl-1)
{
return i-pl+1;
}
}
return -1;
}
int main(void)
{
char s1[120]="123456",s2[120]="45";
cout<<KMP(s1,6,s2,2)<<endl;
return 0;
}