题目描述
https://leetcode-cn.com/problems/longest-palindromic-substring
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
思路:分别从最长位置开始判断是否是回文串,是则跳出当前循环,判断是否是历史最长
class Solution {
public String longestPalindrome(String s) {
if(s==null||s.length()==0){
return "";
}
String res="";
for(int i=0;i<s.length();i++){
for(int j=s.length()-1;j>=0;j--){
String temp=s.substring(i,j+1);
if(huiwen(temp)){
if(temp.length()>res.length()){
res=temp;
}
break;//后续循环不再计算减少时耗
}
}
}
return res;
}
public static boolean huiwen(String temp){
for(int i=0,j=temp.length()-1;i<=j;i++,j--){
if(temp.charAt(i)!=temp.charAt(j)){
return false;
}
}
return true;
}
}