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"
.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases.
public class Solution {
public String shortestPalindrome(String s) {
if(s == null || s.length() ==0) return s;
int index = 0;
for(int i=s.length(); i>=0; i--){
if(isPalindrome(s.substring(0,i))){
index = i;
break;
}
}
if(index==s.length()) return s;
StringBuilder sb = new StringBuilder(s.substring(index));
sb.reverse();
return sb.toString()+s;
}
public boolean isPalindrome(String s){
if(s == null) return false;
if(s.length() == 0) return true;
int i=0; int j=s.length() -1;
while(i<j){
if(s.charAt(i)!=s.charAt(j)){
return false;
} else {
i++;
j--;
}
}
return true;
}
}
思路2:用Longest palindorme substring的思想,从中间生长的法则去find palindorme,目的是为了找到连接到最左边的panlindrome。中心点的范围是[0,n/2]。
这种方法,其实有问题,有test case跑不过。暂时不推荐。等弄明白了再写。
思路3:先找到从左往右数,第一个使他不为palindorme的index,然后把后面的string reverse,然后递归调用解决前面部分的,使他为panlindrome,然后把后面的reverse加在前面。
public class Solution {
public String shortestPalindrome(String s) {
if(s == null || s.length() ==0) return s;
int i=0;
int j=s.length()-1;
while(j>=0){
if(s.charAt(i) == s.charAt(j)){
i++;
}
j--;
}
if(i==s.length()){
return s;
}
String postStr = s.substring(i);
String preStr = new StringBuilder(postStr).reverse().toString();
String midStr = shortestPalindrome(s.substring(0,i));
return preStr + midStr + postStr;
}
}