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"
.
class Solution {
public String shortestPalindrome(String s) {
int len = s.length();
int maxLen = 1;
for (int i = 0; i < len; ++ i){
if (isPalindrome(s, i, i)){
maxLen = Math.max(maxLen, 2*i + 1);
}
if (isPalindrome(s, i, i + 1)){
maxLen = Math.max(maxLen, 2*i + 2);
}
}
StringBuilder sb = new StringBuilder(s);
for (int i = maxLen; i < len; ++ i){
sb.insert(0, s.charAt(i));
}
return sb.toString();
}
public boolean isPalindrome(String s, int i, int j){
int len = s.length();
while (i >= 0&&j < len&&s.charAt(i) == s.charAt(j)){
i --;
j ++;
}
return (i == -1);
}
}