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.

For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".

思路:
在左侧加字符形成回文,要求最短回文,关键是求出左侧最长的回文串。
可以通过两个指针的方法,来找出左侧最长回文,用一个end指针标记这段回文的结束位置。

public String shortestPalindrome(String s) {
    int i = 0, end = s.length() - 1, j = end; char chs[] = s.toCharArray();
    while(i < j) {
        if (chs[i] == chs[j]) {
            i++; j--;
        } else {
            i = 0; end--; j = end;
        }
    }
    return new StringBuilder(s.substring(end+1)).reverse().toString() + s;
}

你可能感兴趣的:(Leetcode 214. Shortest Palindrome)