[leetcode-214]Shortest Palindrome(java)

问题描述:
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”.

分析:这道题我的思路是比较简单的,要补全回文,那就从中间开始,判断是否是有效构造回文的交界点。如果不是的话,就base–,这里可能要注意的一点是对于每一个base而言,都有两种可能,一是奇数型,二是偶数型(自己命名的,,)。这种做法时间复杂度为O(n2),据说还有O(n)的解决方案,是使用的Manacher算法。

运行时间:336ms

public class Solution {
      public String shortestPalindrome(String s) {
        char[] chars = s.toCharArray();
         if(chars.length<=0)
            return "";

        int length = chars.length;
        int base = (length-1)/2;

        boolean isOdd = true;
        while (base>=0){
            if(isValid(chars,base,base+1)) {
                isOdd = false;
                break;
            }
            if(isValid(chars,base,base))
                break;
            base--;
        }
        StringBuilder builder = new StringBuilder();
        int index = length-1;
        while(index>=base){
            builder.append(chars[index--]);
        }
        int oneSize = builder.length();
        if(isOdd)//如果是奇数
            index = oneSize-2;
        else{
            builder.deleteCharAt(oneSize-1);
            index = oneSize-2;
        }
        while(index>=0)
            builder.append(builder.charAt(index--));
        return builder.toString();
    }
    private boolean isValid(char[] chars,int left,int right){
        while(left>=0){
            if(right>=chars.length || chars[left]!=chars[right])
                return false;
            left--;right++;
        }
        return true;
    }
}

你可能感兴趣的:(leetcode)