kmp

#include <bits/stdc++.h>
using namespace std;
int Next[100005];
void getnext(string s){
    int j=0,k=-1;
    int len=s.size();
    Next[0]=-1;
    while(j<len-1){
        if(k==-1||s[j]==s[k]){
            k++,j++;
            if(s[j]==s[k]) Next[j]=Next[k];
            else Next[j]=k;
        }
        else k=Next[k];
    } 
}
int strstr(string s,string t){
    getnext(t);
    int la=s.size(),lb=t.size();
    int i=-1,j=-1;
    while(i<la&&j<lb){
        if(j==-1) i++,j++;
        else if(s[i]==t[j]) i++,j++;
        else j=Next[j];
    }
    if(j==lb) return i-lb;
    return -1;
}
int main()
{
    string s,t;
    cin>>s>>t;
    printf("%d\n",strstr(s,t));
    return 0;
}

 

posted @ 2020-03-11 15:52  Dorom  阅读(142)  评论(0)    收藏  举报