码迷,mamicode.com
首页 > 其他好文 > 详细

poj3461kmp

时间:2014-07-26 17:01:31      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   div   ar   

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

 

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

 

poj3461kmp,布布扣,bubuko.com

poj3461kmp

标签:style   blog   color   os   io   for   div   ar   

原文地址:http://www.cnblogs.com/yigexigua/p/3870170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!