问题
给定一个字符串s,找到s中最长的回文子串。
示例1
输入: "babd"
输出: "bab"
示例2
输入: "cbbd"
输出: "bb"
代码
public class LongestPalindromicSubstring {
public static void main(String[] args) {
String s="babd";
System.out.println(longestPalindrome(s));
}
public static String longestPalindrome(String s) {
if (s==null || s.length()==0){
return "";
}else{
int leftIndex=0,rightIndex=0;
for (int i=0;i<s.length();i++){
int len1=expandAroundCenter(i,i,s);
int len2=expandAroundCenter(i,i+1,s);
int maxLen=Math.max(len1,len2);
if (maxLen>rightIndex-leftIndex){
leftIndex=i-(maxLen-1)/2;
rightIndex=i+maxLen/2;
}
}
return s.substring(leftIndex,rightIndex+1);
}
}
public static int expandAroundCenter(int leftIndex,int rightIndex,String s){
while(leftIndex>=0 && rightIndex<s.length() && (s.substring(leftIndex,leftIndex+1)).equals(s.substring(rightIndex,rightIndex+1))){
leftIndex--;
rightIndex++;
}
return rightIndex-leftIndex-1;
}
}
网友评论