leetcode 214. Shortest Palindrome

Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"

题目在左侧添加最少的字符使s变为回文。

由于只能在左侧添加。问题等价于在s中找到最大的回文s[:i],等价于在倒序字符串的结束部位找到一个最大的匹配串。是一个findStr的变种问题。这里使用KMP算法(KMP算法缓存了匹配串中每个位置与字符串开始位置重复的长度,这样可以不用每次都重头匹配)。另外由于我们寻找的是回文。所以在检索的过程中我们只需检索一半的长度即可。代码如下:

int min(int n1,int n2){
    return n1 < n2 ? n1 : n2;
}
char* shortestPalindrome(char* s) {
    int l = strlen(s);
    if(l == 0){
        return s;
    }
    int KMP[l];//KMP[i]存储当i+1字符匹配错误时,下一个尝试的字符的index
    KMP[0] = 0;
    for(int i = 1; i < l; ++i){
        int j = KMP[i-1];
        while(s[j] != s[i] && j > 0){
            j = KMP[j-1];
        }
        if(s[j] == s[i]){
            KMP[i] = j+1;//从j+1的位置开始匹配
        }else{
            KMP[i] = 0;//从0开始匹配
        }
    }
    char *end = s + l - 1;
    int checkIndex = 0;
    while(checkIndex <= end - s){//检索到结束前的最大匹配串,由于寻找的是回文,所以只需要检索一半就可以了
        char endC = end[0];
        while(checkIndex > 0 && s[checkIndex] != endC ){
            checkIndex = KMP[checkIndex - 1];
        }  
        if(s[checkIndex] == endC){
            ++checkIndex;
        }
        --end;
    }
    //特殊处理下长度为单数的情况
    if(checkIndex == end - s + 1){
        checkIndex = checkIndex*2;
    }else{
        checkIndex = checkIndex*2 - 1;
    }
    //copy结果
    char* ret = malloc(sizeof(char)*(l+(l-checkIndex)+10));
    for(int i = checkIndex; i < l ; ++i){
        ret[l-i-1] = s[i];
    }
    strcpy(ret+l-checkIndex,s);
    return ret;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值