KMP算法

#include
#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章