Problem

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"

Solution

class Solution {
    public String shortestPalindrome(String s) {
        int len = s.length();
        int i = len;
        for (i = len; i >= 0; i--) {
            if (isPalindrome(s.substring(0, i))) break;
        }
        StringBuilder sb = new StringBuilder();
        
        if (i < 0) {
            sb.append(s).reverse();
            return sb.toString()+s;
        }
        
        sb.append(s.substring(i)).reverse();
        return sb.toString() + s;
    }
    private boolean isPalindrome(String s) {
        int i = 0, j = s.length()-1;
        while (i <= j) {
            if (s.charAt(i++) != s.charAt(j--)) return false;
        }
        return true;
    }
}

linspiration
161 声望53 粉丝