LeetCode Shortest Palindrome

本文介绍了解决LeetCode中最短回文串问题的方法,采用KMP算法构造特殊字符串S,通过计算前缀函数找到最大匹配前缀,进而得出最短回文串。

LeetCode Shortest Palindrome

题目

这里写图片描述

思路

其实原本想了一种算法,自己算了下大概复杂度为O(n^2);
想着定是不过了,于是看了Discuss里面的题解;
附上链接:KMP思路题解
而后把原来的题解翻译了一下,改成了C语言的;
详见代码。

代码

//通过构造一个字符串S,再利用KMP算法可以解决这个问题
//其中S=(输入的s)+(一个绝不会在s中出现的符号,比如#)+(s的翻转rev_s)
//在用完KMP算法之后,我们可以得到一个数组p
//数组p上的值为每个字符的前缀函数的值(详情看KMP算法)
//我们只需要看p中的最后一个值即可
//因为它显示了rev_s中最大的、与原有字符串s的前缀匹配上的子串
//最后我们只需要将前k个rev_s中的字符和原有字符串相连即可
//其中k为p的最后一个值和原有字符串s的长度的差值

char * shortestPalindrome(char * s) {

    int length = strlen(s);
    int Length = 2 * length + 1;
    char * rev_s = (char*)malloc(sizeof(char) * (length + 2));
    char * l = (char*)malloc(sizeof(char) * (2 * length + 2));

    for (int i = length - 1; i >= 0; i--) {
        rev_s[i] = s[length - i - 1];
    }
    rev_s[length] = '\0';

    for (int i = 0; i < length; i++) l[i] = s[i];
    l[length] = '#';
    for (int i = 0; i < length; i++) l[i + length + 1] = rev_s[i];
    l[2 * length + 1] = '\0';

    int * p = (int*)malloc(sizeof(int) * Length);
    for (int i = 0; i < Length; i++) p[i] = 0;

    for (int i = 1; i < Length; i++) {
        int j = p[i - 1];
        while (j > 0 && l[i] != l[j]) j = p[j - 1];
        p[i] = (j += l[i] == l[j]);
    }

    char * sub_s = (char*)malloc(sizeof(char) * (2 * length - p[Length - 1] + 1));
    for (int i = length - p[Length - 1] - 1; i >= 0; i--) sub_s[i] = rev_s[i];
    for (int i = 0; i < length; i++) sub_s[i + length - p[Length - 1]] = s[i];
    sub_s[2 * length - p[Length - 1]] = '\0';

    free(rev_s);
    free(l);

    return sub_s;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值