首页 > 其他 > 详细

KMP模板

时间:2020-02-11 11:19:12      阅读:38      评论:0      收藏:0      [点我收藏+]
#include<iostream>
#include<cstring>

using namespace std;

char s[1005],str[105];
int Next[105];

void Get_KMP()
{
    int m = strlen(str);
    int i=0,j=-1;
    Next[0] = -1;
    while(i<m)
    {
        if(j == -1 || str[i] == str[j])
        {
            ++i;++j;
            Next[i] = (str[i]!=str[j])?j:Next[j];
        }
        else 
        {
            j = Next[j];
        }
    }
    return ;
}

int KMP()
{
    int n = strlen(s);
    int m = strlen(str);
    int i=0, j=0;
    while(j<m && i<n)
    {
        if(j == -1 || s[i] == str[j])
        {
            i++;j++;
        }
        else
        {
            j = Next[j];
        }
        
    }
    if(j>=m) return i-m;
    else return -1;
}

int main()
{
    ios::sync_with_stdio(false);
    cin >> s >> str;
    Get_KMP();
    printf("%d\n",KMP());
    return 0;
}

KMP模板

原文:https://www.cnblogs.com/sdutzxr/p/12294066.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!