LIGHTOJ 1258 – MAKING HUGE PALINDROMES 【KMP】

题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1258

题意:为了使原串变为回文串,可任意添加字符,求变为回文串之后字符的长度。

解法:求字符串与其反串的最大公共长度len,则最后回文字符串的长度为:原串长度*2-len;

代码:

#include <stdio.h>  
#include <iostream>  
#include <math.h>  
#include <stdlib.h>  
#include <ctype.h>  
#include <algorithm>  
#include <vector>  
#include <string.h>  
#include <queue>  
#include <stack>  
#include <set>  
#include <map>  
#include <sstream>  
#include <time.h>  
#include <malloc.h>  

using namespace std;
#define LL  long long

void get_next(char x[], LL m, LL Next[])
{
    LL i, j;
    j = Next[0] = -1;
    i = 0;
    while (i < m)
    {
        while (-1 != j && x[i] != x[j]) j = Next[j];
        Next[++i] = ++j;
    }
}

LL Next[1001000];
long long KMP(char x[], LL m, char y[], LL n)//x模式串 y主串 
{
    LL i, j, ans = 0;
    i = j = 0;
    get_next(x, m, Next);
    while (i < m && j < n)
    {
        if (j ==-1 || x[j] == y[i])
        {
            i++;
            j++;
        }
        else
            j = Next[j];
    }
    return n + m - j;
}
char a[1000100], b[1000100];

int main()
{
    LL t;
    scanf("%lld",&t);
    for (LL i = 1; i <= t;i++)
    { 
        scanf("%s", a);
        LL n = strlen(a);

        for (LL k = 0; k < n; k++)
            b[n - k -1] = a[k];
        long long tmp = KMP(b, n, a, n);
        printf("Case %lld: ",i);
        printf("%lld\n",tmp);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值