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

poj 2406 Power Strings KMP匹配

时间:2014-08-04 21:38:08      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:style   color   os   io   问题   ar   line   size   

对于数组s[0~n-1],计算next[0~n](多计算一位)。

考虑next[n],假设t=n-next[n],如果n%t==0,则t就是问题的解,否则解为1。

这样考虑:

比如字符串"abababab",

            a  b a b a b a b *

next     -1 0 1 2 3 4 5 6  7

考虑这样的模式匹配,将"abababab#"当做主串,"abababab*"当做模式串,于是进行匹配到n(n=8)时,出现了不匹配:

 主串      abababab#

 模式串   abababab*

于是模式串需要回溯到next[*]=7,这之前的主串和模式串对应相等,于是需要模式串向右滚动的位移是d=n-next[n]=2,即:

            123456789 

主串      abababab#

模式串       abababab*

于是可以看出,s[0~1]=s[3~4]=s[5~6]=s[7~8]。

所以位移d=n-next[n]可以看作是构成字符串s的字串(如果n%d==0,存在这样的构成),相应的重复次数也就是n/d。

#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int len;
int next[1000005];
char s[1000005];
int kmp_next()
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<len)
    {
        if(j==-1||s[i]==s[j])
        {
            i++;j++;
            next[i]=j;

        }
        else
            j=next[j];
    }
    int x=i-next[i];//碰到不匹配的向前滚动的位移
    if(len%x==0)
        return x;
    else
        return len;
}

int main()
{

    while(scanf("%s",s)!=EOF)
    {
        if(s[0]=='.')
            break;
        len=strlen(s);
        int ans=kmp_next();
        ans=len/ans;
        printf("%d\n",ans);
    }
    return 0;
}


poj 2406 Power Strings KMP匹配,布布扣,bubuko.com

poj 2406 Power Strings KMP匹配

标签:style   color   os   io   问题   ar   line   size   

原文地址:http://blog.csdn.net/asuxiexie/article/details/38374143

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