首页 > 编程语言 > 详细

hihoCoder week3 KMP算法

时间:2018-11-06 19:01:36      阅读:155      评论:0      收藏:0      [点我收藏+]

题目链接

https://hihocoder.com/contest/hiho3/problems

 

kmp算法

#include <bits/stdc++.h>
using namespace std;

const int N = 1e6 + 10;
char s[N], t[N];
int nxt[N]; 

// ababaca
void getNext(int len)
{
    nxt[0] = -1;
    int k = -1;
    for(int i=1; i<len; i++) {
        while(k!=-1 && t[i]!=t[k+1])
            k = nxt[k];
        if(t[k+1] == t[i])
            k++;
        nxt[i] = k;
    }
    /*
    for(int i=0; i<len; i++){
        cout << nxt[i]<<" "; 
    }
    */
}
void kmp()
{
    int lt = strlen(t), ls = strlen(s);
    // nxt[i] 表示的是 i位可以退回的位置
    getNext(lt);
    int num = 0;
    int k = -1;
    for(int i=0; i<ls; i++) {
        while(k!=-1 && t[k+1] != s[i])
            k = nxt[k];
        if(t[k+1] == s[i])
            k++;
        if(k == lt-1) {
            num++;
            k = nxt[k];
        }
    }
    printf("%d\n",num);
}

int main()
{
    // freopen("in.txt", "r", stdin);
    int T; scanf("%d", &T);
    while(T--) {
        scanf("%s %s", t, s);
        kmp();
    }
    return 0;
}

 

hihoCoder week3 KMP算法

原文:https://www.cnblogs.com/Draymonder/p/9917048.html

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