KMP algorithm

#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;


int main()
{
    char str[100],s[100];
    cin>>str>>s;
    int l1=strlen(str);
    int l2=strlen(s);
    int next[l2];
    int k=-1,j=0;next[0]=-1;
    while(j<l2)
    {
        if(k==-1||s[k]==s[j])
            next[++j]=++k;
        else
            k=next[k];
    }
    j=0;
    int i=0;
    while(i<l1&&j<l2)
    {
        if(j==-1||str[i]==s[j])
        {
            j++;
            i++;
        }
        else
        {
            j=next[j];
        }
    }
    if(j==l2)
    {
        cout<<i-j<<endl;
    }
    else cout<<"no"<<endl;
}

Guess you like

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