现在的位置: 首页 > 综合 > 正文

poj 2752 Seek the Name, Seek the Fame KMP

2018年04月29日 ⁄ 综合 ⁄ 共 901字 ⁄ 字号 评论关闭

对于KMP算法中next函数的应用

题意是对于一个字符串的前缀和后缀比较是否相等,再把相等的可能按字符串长度进行输出

#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];
    }
     //for(int i=0;i<len;i++)
        //printf("%d\n",next[i]);
   // int x=i-next[i];//碰到不匹配的向前滚动的位移
   // if(len%x==0)
     //   return x;
   // else
      //  return len;
}
void output(int qq)
{
     if(next[qq]!=0)
       {
            output(next[qq]);
             printf("%d ",next[qq]);//递归的往前找相匹配的
       }
}
int main()
{

    while(scanf("%s",s)!=EOF)
    {
        if(s[0]=='.')
            break;
        len=strlen(s);
        int ans=kmp_next();
       // for(int i=len;i>0;i--)
       // {
           // if(next[i]!=0||(next[i]==0&&next[i+1]!=0))
              //  printf("%d ",next[i]+1);
       // }
        output(len);
        printf("%d\n",len);
        //ans=len/ans;
       // printf("%d\n",ans);
    }
    return 0;
}

抱歉!评论已关闭.