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”.
我的思路:从给定字符串中间一个元素开始向左遍历,判断该位置是否可以作为返回结果的中点/中点右边的元素
时间为392ms
程序如下:
public String shortestPalindrome(String s) {
if(s==null||s.length()<2)
return s;
int len=s.length();
int index=(len-1)/2;
boolean mid=true;
while(index>=0){
if(checkMid(s, index, mid)){
break;
}
mid=!mid;
if(checkMid(s, index, mid))
break;
mid=!mid;
index--;
}
System.out.println(index);
System.out.println(mid);
StringBuilder rst=new StringBuilder();
int index2;
if(mid)
index2=2*index+1;
else
index2=2*(index);
for(int i=s.length()-1;i>=index2;i--){
rst.append(s.charAt(i));
}
rst.append(s);
return rst.toString();
}
private boolean checkMid(String s, int index,boolean mid){
int left=index-1;
int right;
if(mid)
right=index+1;
else {
right=index;
}
while(left>=0){
if(s.charAt(left)!=s.charAt(right))
return false;
left--;
right++;
}
return true;
}
但讨论区(https://leetcode.com/discuss/36865/my-java-solution-o-n-2-do-not-need-to-use-manachers-algorithm)中的这个方法,实现起来貌似更简洁一些:
但是效率低一些,时间为856ms
public class Solution {
public String shortestPalindrome(String s) {
if(isPalindrome(s))return s;
int i=s.length();
while(i>0){
String sub1 = s.substring(0,i--);
if(isPalindrome(sub1))break;
}
i++;
String sub2 = s.substring(i);
StringBuilder sb = new StringBuilder();
for(int j=sub2.length()-1;j>=0;j--){
sb.append(sub2.charAt(j));
}
for(int j=0;j<s.length();j++){
sb.append(s.charAt(j));
}
return sb.toString();
}
private boolean isPalindrome(String s){
int i=0,j=s.length()-1;
while(i<j){
if(s.charAt(i++)!=s.charAt(j--))return false;
}
return true;
}
}