题目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
分析:
class Solution {
public String longestPalindrome(String s) {
//palindromic回文,指其正序和反序一样。
//找出字符串中最长的回文字符串
//思路:定义一个方法判断是否为回文,每次更新获取最长的长度
String res="";
char []chs=s.toCharArray();
//已经匹配到符合条件的长度,只有比其更长的回文才会被更新
int curLength=0;
for(int i=0;i<s.length();i++){
if(isPalindrome(chs,i-curLength-1,i)){
//判断到该位置是否为回文,若是回文
//成对
res=s.substring(i-curLength-1,i+1);
curLength+=2;//更新
}else if(isPalindrome(chs,i-curLength,i)){
//单个判断
res=s.substring(i-curLength,i+1);
curLength+=1;
}
}
return res;
}
public boolean isPalindrome(char [] chs,int start,int end){
if(start<0) return false;
while(start<end){
if(chs[start++]!=chs[end--]){
return false;
}
}
return true;
}
}