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”
public class Solution {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(longestPalindrome("bbbab"));
}
public static String longestPalindrome(String s) {
if(s.length() <= 1) return s;
boolean[][] P = new boolean[s.length()][s.length()];
String res = new String();
//单字符字符串肯定是回文
for(int i = 0; i < s.length();i++) P[i][i] = true;
int max = 0;
for(int i = 0; i < s.length();i++)
{
for(int j = 0; j < i; j++)
{
//s中索引为j的字符与索引为i的字符相同,且(从j+1到i-1之间字符串是回文,或者i-j<=2意思是两个索引相邻,只间隔一个字符两种情况)
P[j][i] = (s.charAt(j) == s.charAt(i) && (i-j <= 2 || P[j+1][i-1]));
if(P[j][i])
{
if(i-j + 1 > max)
{
max = i-j+1;
res = new String(s.substring(j,i+1));
}
}
}
}
if(res.length()<=1){
res = s.charAt(0)+"";
}
return res;
}
}
通过一个二维数组来记录字符串从j到i的子串是否是回文