kmp算法 和例题 poj1961

题目   http://poj.org/problem?id=1961

刚开始做这个不知道什么是kmp算法    自己看了很多书籍介绍  没看懂   最后还是看课本知道了一点点

首先我来介绍kmp   算法吧

    next[ j ] 等于   一共分三种情况    1. next [ j ]=0  当 j =1时 ;2. MAX { 1<K< j 且‘p1....p(k-1)'=' p(j-k+1)...p(j-1)'} ;3 next[ j ]=1 其他情况哦;

   第一次匹配          当i=3

假设   a b a b c a b c a c b a b

          a b c  

                j=3;

第二次匹配

                 i=3 -> i=7

          a b a b c a b c a c b a b

                a b c a c

                 j=5;

第三次匹配

                 j=1;

                           i=7  --->i=11

          a b a b c a b c a c b a b

                       (a)b c a c

                       j=6;

              kmp算法重点是在于 计算next[ j ]的值哦

            下面是计算的next的值

             j       1  2  3  4  5  6  7  8

     模式串     a  b  a  a  b  c  a  c

     next[ j ]    0  1  1  2  2  3  1  2

void get_next(char *s1,char *next)
{
    int i=0,j=-1;
    next[0]=-1;
    int len=strlen(s1);
    while(i<len)
    {
        if(j==-1||s1[i]==s1[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else j=next[j];
    }
}


现在给出   ac   poj1961 的代码哦

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define maxn 1000002
char s1[maxn];
int next[maxn];

void get_next()
{
    int i=0,j=-1;
    next[0]=-1;
    int len=strlen(s1);
    while(i<len)
    {
        if(j==-1||s1[i]==s1[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else j=next[j];
    }
}
int main()
{
    int n,test=0,i,len;
    while(scanf("%d",&n)&&n)
    {
        scanf("%s",s1);
        get_next();

        printf("Test case #%d\n",++test);
        for(i=2;i<=n;i++)   //求出前i个字符中重复串
        {
           len=i-next[i];
           if(i%len==0&&i/len>1)
           printf("%d %d\n",i,i/len);
        }
        printf("\n");
    }
    return 0;
}


 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值