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

POJ 2752 Seek the Name, Seek the Fame

2019年01月07日 ⁄ 综合 ⁄ 共 745字 ⁄ 字号 评论关闭

        题目大意:给你一个字符串,让你找出这个字符串中有多少满足下列条件的字串:该字串既是母串的前缀,也是字串的后缀。

        解题思路:此题着重考察对KMP 算法中的Next 数组的理解。

代码如下:

#include<cstdio>
#include<string>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std ;
const int MAXN = 400005 ;
char s[MAXN] ;
int len ;
int Next[MAXN] ;
int ans[MAXN] ;
void init()
{
    memset(Next , 0 , sizeof(Next)) ;
    memset(ans , 0 , sizeof(ans)) ;
}
void getNext(char *s)
{
    int i = 0 ;
    len = strlen(s) ;
    Next[0] = -1 ;
    int j  = -1 ;
    while (i < len)
    {
        if(j == -1 || s[i] == s[j])
        {
            j ++ ;
            i ++ ;
            Next[i] = j ;
        }
        else
            j = Next[j] ;
    }
}
void solve()
{
    getNext(s) ;
    int cnt = 0 ;
    int k = Next[len - 1] ;
    ans[cnt ++] = len ;
    while(k != -1)
    {
        if(s[k] == s[len - 1])
        {
            ans[cnt ++] = k + 1 ;
        }
        k = Next[k] ;
    }
    int i ;
    for(i = cnt - 1 ; i >= 0 ; i --)
    {
        printf("%d" , ans[i]) ;
        if(i >= 1) printf(" ") ;
    }
    printf("\n") ;
}
int main()
{
    while (scanf("%s" , s) != EOF)
    {
        init() ;
        solve() ;
    }
    return 0 ;
}

抱歉!评论已关闭.