KMP介绍->POJ3461

6 篇文章 0 订阅
KMP算法介绍

KMP算法要解决的问题就是在字符串(也叫主串)中的模式(pattern)定位问题。说简单点就是我们平时常说的关键字搜索。模式串就是关键字(接下来称它为P),如果它在一个主串(接下来称为T)中出现,就返回它的具体位置,否则返回-1(常用手段)。

详解算法可以参考,写的非常详细:
http://www.cnblogs.com/yjiyjige/p/3263858.html


题意:

求一个模式串在主串中出现的次数

题解:

很容易想到这题要用KMP算法求解,匹配成功一次就给ans+1,函数返回参数,输出答案即可。


代码:

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std ;
#define MAX 1000005
int next[MAX] ;
char word[MAX] , temp[MAX] ;
void kmp_pre(char x[] , int m ,int next[])
{
    int i , j ;
    j = next[0] = -1 ;
    i = 0 ;
    while(i < m)
    {
        while(-1 != j && x[i] != x[j]) j = next[j] ;
        if(x[++i] == x[++j]) next[i] = next[j] ;
        else next[i] = j ;
    }
}
int KMP_Count(char x[] , int m ,char y[] , int n)
{
    int i , j ;
    int ans = 0 ;
    kmp_pre(x , m , next) ;
    i = j = 0 ;
    while(i < n)
    {
        while(-1 != j && y[i] != x[j]) j = next[j] ;
        i ++ ; j ++ ;
        if(j >= m)
        {
            ans ++ ;
            j = next[j] ;
        }
    }
    return ans ;
}
int main()
{
    int T ;
    scanf("%d" , &T) ;
    getchar() ;
    while(T --)
    {
        scanf("%s" ,temp) ;
        scanf("%s" ,word) ;
        printf("%d\n", KMP_Count(temp , strlen(temp) , word , strlen(word))) ;
    }
    return 0 ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值