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"
.
分析:
就是找出从原字符串中从第一个字符开始能够组成的最长palindome. 然后把原字符串中后面部分reverse后放在前面,这样整个字符串就是palindrome, 并且长度最小。
1 public class Solution { 2 public String shortestPalindrome(String s) { 3 if (s == null || s.length() <= 1) 4 return s; 5 int size = 0; 6 for (int i = 0; i <= (s.length() - 1) / 2; i++) { 7 size = Math.max(size, maxSize(s, i, i)); 8 size = Math.max(size, maxSize(s, i, i + 1)); 9 } 10 String str = s.substring(size); 11 StringBuilder sb = new StringBuilder(str); 12 sb.reverse(); 13 return sb.toString() + s; 14 } 15 16 private int maxSize(String s, int left, int right) { 17 while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { 18 left--; 19 right++; 20 } 21 if (left == -1) { 22 return right - left - 1; 23 } 24 return 0; 25 } 26 }