解法一:双指针
class Solution {
public String longestPalindrome(String s) {
if(s.length()<=1)
return s;
int s1=0,e1=0;
for(int i=1;i<s.length();i++){
int left=i,right=i;
while(left>=0 && right<s.length() && s.charAt(left)==s.charAt(right)){
left--;
right++;
}
if(right-(left+1)>e1-s1){
s1=left+1;
e1=right;
}
left=i-1;
right=i;
while(left>=0 && right<s.length() && s.charAt(left)==s.charAt(right)){
left--;
right++;
}
if(right-(left+1)>e1-s1){
s1=left+1;
e1=right;
}
}
return s.substring(s1,e1);
}
}
解法二:马拉车算法,难点在于利用已经比较的条件
class Solution {
public String longestPalindrome(String s) {
String str=translateS(s);
int dp[]=new int[str.length()];
int pos=0,mx=0,id=0;
for(int i=1;i<str.length();i++){
if(mx>i){
if(dp[id-(id-i)]<mx-i)
dp[i]=dp[id-(id-i)];
else
dp[i]=mx-i;
}
else
dp[i]=1;
while(dp[i]+i<str.length() && str.charAt(i-dp[i])==str.charAt(i+dp[i]))
dp[i]++;
if(dp[i]+i>mx){
mx=dp[i]+i;
id=i;
}
if(dp[id]>dp[pos])
pos=id;
}
int start=(pos-dp[pos])/2;
return s.substring(start,start+dp[pos]-1);
}
String translateS(String s){
StringBuffer sb=new StringBuffer("$#");
for(int i=0;i<s.length();i++)
sb.append(s.charAt(i)).append('#');
return sb.toString();
}
}