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.

For example:

Given "aacecaaa", return "aaacecaaa".

Given "abcd", return "dcbabcd".

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases.

思路:暴力解法:每次算s.substring(0,i) i属于s.length-1 到0,目的就是找到最大的以0为起点的最大palindrome. 但是这种做法time out。

public class Solution {
    public String shortestPalindrome(String s) {
        if(s == null || s.length() ==0) return s;
        int index = 0;
        for(int i=s.length(); i>=0; i--){
            if(isPalindrome(s.substring(0,i))){
                index = i;
                break;
            }
        }
        if(index==s.length()) return s;
        StringBuilder sb = new StringBuilder(s.substring(index));
        sb.reverse();
        return sb.toString()+s;
    }
    
    public boolean isPalindrome(String s){
        if(s == null) return false;
        if(s.length() == 0) return true;
        int i=0; int j=s.length() -1;
        while(i<j){
            if(s.charAt(i)!=s.charAt(j)){
                return false;
            } else {
                i++;
                j--;
            }
        }
        return true;
    }
}
思路2:用Longest palindorme substring的思想,从中间生长的法则去find palindorme,目的是为了找到连接到最左边的panlindrome。中心点的范围是[0,n/2]。

这种方法,其实有问题,有test case跑不过。暂时不推荐。等弄明白了再写。

思路3:先找到从左往右数,第一个使他不为palindorme的index,然后把后面的string reverse,然后递归调用解决前面部分的,使他为panlindrome,然后把后面的reverse加在前面。

public class Solution {
    public String shortestPalindrome(String s) {
        if(s == null || s.length() ==0) return s;
        int i=0;
        int j=s.length()-1;
        while(j>=0){
            if(s.charAt(i) == s.charAt(j)){
                i++;
            }
            j--;
        }
        if(i==s.length()){
            return s;
        }
        String postStr = s.substring(i);
        String preStr = new StringBuilder(postStr).reverse().toString();
        String midStr = shortestPalindrome(s.substring(0,i));
        return preStr + midStr + postStr;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值