hihoCoder week3 KMP算法

题目链接

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;
}

猜你喜欢

转载自www.cnblogs.com/Draymonder/p/9917048.html
今日推荐