码迷,mamicode.com
首页 > 其他好文 > 详细

KMP模板

时间:2020-02-11 11:29:36      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:clu   std   include   str   with   ||   kmp   strlen   oid   

#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模板

标签:clu   std   include   str   with   ||   kmp   strlen   oid   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!