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"
.
public class Solution {
public String shortestPalindrome(String s) {
if (s.length() <= 1) return s;
int end = 0;
for (int i = s.length()/2+1; i >= 0; i--) {
int len1 = expand(s, i, i);
int len2 = expand(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end) {
end = i + len / 2;
break;
}
}
if (end==s.length()-1) return s;
StringBuilder sb= new StringBuilder();
for (int i = s.length()-1; i > end; i--) {
sb.append(s.charAt(i));
}
sb.append(s);
return sb.toString();
}
private int expand(String s, int left, int right){
while (left>=0 && right<s.length() && s.charAt(left)==s.charAt(right)){
left--;
right++;
}
if ((left+1)!=0 ) return 0;
return right-left-1;
}
}