Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
一、逐一判断法
public String longestPalindrome(String s) {
String res;
int left=0,right=0;
int max=1;
if(s.length()==0) return res="";
for(int i=0;i<s.length();i++){
for(int k=s.length()-1;k>i;k--){
if(s.charAt(i)==s.charAt(k)){
int m=i;
int n=k;
if((k-i+1)%2==0){
while(m!=n-1){
if(s.charAt(m)!=s.charAt(n))
break;
m++;
n--;
}
if(m==n-1&&k-i+1>max&&s.charAt(m)==s.charAt(n)) {
max=k-i+1;
left=i;
right=k;
}
}
else{
while(m!=n){
if(s.charAt(m)!=s.charAt(n))
break;
m++;
n--;
}
if(m==n&&k-i+1>max) {
max=k-i+1;
left=i;
right=k;
}
}
}
}
}
res=s.substring(left,right+1);
return res;
}
先找出回文字串,再和保存好的最长回文子串的MAX值进行判断是否储存当前字串的信息。
网友评论