poj3461kmp

求模式串在原串出现次数。

 

#include <cstdio>

#include <cstring>

#include <algorithm>

#include <climits>

#include <string>

#include <iostream>

#include <map>

#include <cstdlib>

#include <list>

#include <set>

#include <queue>

#include <stack>



using namespace std;



const int maxn=1111111;



int next[maxn];



void getnext(char *s)

{

    int len=strlen(s);

    int j=-1;int i=0;

    next[0]=-1;

    while(i<len){

        if(j==-1||s[i]==s[j]){

            i++;j++;next[i]=j;

        }

        else{

            j=next[j];

        }

    }

}//求next 数组函数   next[j]  表示从 str[j-1]向前和从头str[0]向后 最长相同串的长度

int ans;

void solve(char *s,char  *s1)

{

    int j=0;

    int len=strlen(s);int len1=strlen(s1);

    for(int i=0;i<len1;i++){

        if(j>0&&s1[i]!=s[j]) j= next[j]; //失配之后 将 str[next[j]] 与 str1[i] 比较

        if(s[j]==s1[i]) j++;

        if(j==len){

            ans++;

            j=next[j];  //找到答案 后继续失配。。

        }

    }

    cout<<ans<<endl;

}

char str[maxn];char str1[maxn];

int main()

{

    int Icase;

    cin>>Icase;

    while(Icase--){

        scanf("%s",str);scanf("%s",str1);

        ans=0;

        getnext(str);

        solve(str,str1);

    }

    return 0;

}

 

你可能感兴趣的:(poj)