hdu1686

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000000+9;
const int maxn1 = 10000+9;
char a[maxn];
char b[maxn1];
int nextval[maxn1], len1, len2;

void get_nextval()
{
    int i = 0, j = -1;
    nextval[0] = -1;
    while(i < len2)//它會判斷到i = len2 是停止 即 nextval[len2] = x;(某個值)
    {
        if(j == -1 || b[i] == b[j])
        {
            if(b[++i] != b[++j]) nextval[i] = j;
            else  nextval[i] = nextval[j];
        }
        else j = nextval[j];
    }
}

int kmp_search()
{
    get_nextval();
    int i = 0,  j = 0, sum = 0;
    while(i < len1 && j <= len2)//當j等於len2時 a[i] != b[j] = b[len2] 這時 j = nextval[j] 它會繼續找 如第二個例子 相當於4個字符 實際只要三個與原串匹配
    {
        if(j == -1 || a[i] == b[j]) ++i, ++j;
        else j = nextval[j];
        if(j == len2)
        {
            ++sum;
        }
    }
    return sum;
}

int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        cin >> b >> a;
        len1 = strlen(a);
        len2 = strlen(b);
        int w = kmp_search();
        printf("%d\n", w);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章