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;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/862a47aa53a4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞