UVA 11475 Extend to Palindrome KMP

题意:给出一个字符串,求在后面加上最少的字符,是其成为回文串。

思路:很容易得到,求出原串的最长回文后缀,在把其他字符添上即可。

           这里我们用kmp来做。

           因为kmp是考虑的前缀的匹配的程度,我们要把后缀转化成前缀。一个反转操作即可。

第一种方法,是将两个串拼接一起,以:反转串-原串的顺序,然后求一遍fail函数,最后的fail[len-1]的结果就蕴含了匹配的长度。

代码如下:

#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

const int MAX = 200010;

char str[MAX];
char T[MAX<<1];
int f[MAX<<1];

int main(void)
{
    //freopen("input.txt","r",stdin);
    while(scanf("%s",str) != EOF){
        int n = strlen(str);
        int len = 0;
        for(int i = n - 1; i >= 0; --i)
            T[len++] = str[i];
        T[len++] = '$';
        for(int i = 0; i < n; ++i)
            T[len++] = str[i];
        f[0] = f[1] = 0;
        for(int i = 1; i < len; ++i){
            int j = f[i];
            while(j && T[i] != T[j]) j = f[j];
            f[i+1] = T[i] == T[j]? j + 1: 0;
        }
        printf("%s",str);
        for(int i =  n - f[len-1] - 2; i >= 0 ; --i)
            putchar(str[i]);
        putchar('\n');
    }
    return 0;
}

第二种方法是:将反转串作为模式串,原串作为待匹配的串,求出匹配长度即可。

#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

const int MAX = 200010;

char str[MAX];
char rstr[MAX];
int f[MAX];


int main(void)
{
    //freopen("input.txt","r",stdin);
    while(scanf("%s",str) != EOF){
        int len = strlen(str);
        for(int i = 0; i < len; ++i)
            rstr[len - 1 - i] = str[i];
        rstr[len] = 0;
        f[0] = f[1] = 0;
        for(int i = 1; i < len; ++i){
            int j = f[i];
            while(j && rstr[j] != rstr[i]) j = f[j];
            f[i+1] = rstr[i] == rstr[j]? j + 1: 0;
        }
        int j = 0;
        for(int i = 0; i < len; ++i){
            while(j && rstr[j] != str[i]) j = f[j];
            if(rstr[j] == str[i]) j++;
        }
        printf("%s",str);
        for(int i = len - j - 1; i >= 0; --i)
            putchar(str[i]);
        putchar('\n');
    }
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值