KMP algorithm and its optimization

Damn, the KMP algorithm that has been confusing for a long time is finally solved


#include<iostream>

#include<cstring>

using namespace std;
int next[100];
void getnext(char str[100])
{
int i,j,len=strlen(str);
      j=0,i=1;next[1]=0;    // j 代表后缀,i 代表前缀 
while(i<=len-1)
{
  if(j==0||str[i]==str[j])
  {
i++;j++;
if(str[i]!=str[j])
next[i]=j;
        else
        next[i]=next[j];
      }
  else
  { j=next[j];    }  } } int KMP(char s1[],char s2[],int pos) { int i=pos,j=1; s1[0]=strlen(s1); s2[0]=strlen(s2); while(i<s1[0]&&j<s2[0]) {
 










if(j==0||s1[i]==s2[j])
{
i++;j++;
}
else
j=next[j];
}
if(j==s2[0])
return i-s2[0];
else
return -1;
 } 
int main()
{
char s1[100],s2[100];

cin>>s1>>s2;

       int pos;

cin>>post;

    getnext(s2);
    cout<<KMP(s1,s2,pos);
return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325608713&siteId=291194637