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

KMP

时间:2019-08-28 10:49:22      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:namespace   name   bsp   end   max   cin   pre   ret   next   

#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1000000+7;
char s[maxn], p[maxn];
int net[maxn];
int lens, lenp;
void getnext() {
    net[0] = -1;
    int i = 0,j = -1;
    while (i < lenp - 1) {
        if (j == -1 || p[i] == p[j]) 
net[++i] = ++j;
        else j = net[j];
    }
}
int kmp() {
    lens = strlen(s);
    lenp = strlen(p);
    int i = 0, j = 0;
    getnext();
    while (i < lens && j < lenp) {
        if (s[i] == p[j] || j == -1) i++, j++;
        else j = net[j];
    }
    if (j == lenp) return i - j;
    else return -1;
}
int main() {
    cin >> s;
    cin >> p;
    int ans = kmp();
    cout << ans << endl;
    return 0;
}

 

KMP

标签:namespace   name   bsp   end   max   cin   pre   ret   next   

原文地址:https://www.cnblogs.com/wronin/p/11422394.html

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