IT民工
加油!

  字符串模式匹配,KMP算法相当高效,O(n + m)。关键在求出模式串的next数组,

求完这个,一些基本的题应该都是没有问题了的,文本串只要扫描一次。求模式串在文

本中出现的次数,当匹配模式串的最后一个字符时,就说明出现了一次。

/*Accepted    1192K    94MS    C++    987B    2012-08-01 09:21:25*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

const int MAXT = 1000100;
const int MAXW = 10010;
char T[MAXT], W[MAXW];
int next[MAXW], lt, lw;

void Make_Next(char *w)
{
    int i = 0, j = -1;
    next[0] = -1;
    lw = strlen(w);
    while(i < lw)
    {
        if(-1 == j || w[i] == w[j])
        {
            ++ i, ++ j;
            if(w[i] != w[j])
                next[i] = j;
            else
                next[i] = next[j];

        }
        else
            j = next[j];
    }
}

int KMP(char *w, char *t, int pos)
{
    int i = pos, j = 0, ans = 0;
    Make_Next(w);
    lt = strlen(t);
    while(i < lt)
    {
        if(j == -1 || t[i] == w[j]) ++ i, ++ j;
        else j = next[j];
        if(lw == j) ++ ans, j = next[j];
    }
    return ans;
}

int main()
{
    int c;
    scanf("%d", &c);
    while(c --)
    {
        scanf("%s%s", W, T);
        printf("%d\n", KMP(W, T, 0));
    }
    return 0;
}

 

 

 

posted on 2012-08-01 09:29  找回失去的  阅读(260)  评论(0编辑  收藏  举报