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"
public class ShortestPalindrome {
public static void main(String[] args) {
/**
* 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"
*/
System.out.println(shortestPalindrome("aacecaaa"));
System.out.println(shortestPalindrome("abcd"));
}
public static String shortestPalindrome(String s)
{
if (s == null || s.length() <= 1)
{
return s;
}
int end = s.length() - 1, i = 0, j = end;
while (i < j)
{
if (s.charAt(i) == s.charAt(j))
{
i++;
j--;
}
else
{
i = 0;
j = --end;
}
}
return new StringBuilder(s.substring(end + 1)).reverse().append(s).toString();
}
}
参考链接: