朴素算法
#include <iostream>
using namespace std;
int BF(string s1, string s2, int pos)
{
int i=pos;
int j=0;
while(i<s1.length() && j<s2.length())
{
if(s1[i] == s2[j])
{
i++;
j++;
}
else
{
i = i-j+1;
j = 0;
}
}
if(j > s2.length()-1)
{
return i-j;
}
else
{
return -1;
}
}
int main()
{
string s1 = "appleisfriut";
string s2 = "is";
int pos = 0;
int p = BF(s1,s2,pos);
cout<<p<<endl;
}
KMP算法
void get_next(string str,int *next)
{
int i,j;
i=1;
j=0;
next[1]=0;
while(i<str[0])
{
if(j==0 || str[i] == str[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
KMP算法主要是解决next数组的问题