题目描述
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"
思路分析
1.回文字符串的子串也是回文,比如P[i][j](比如以i开头以j结束的子串)是回文字符串,那么P[i+1][j-1]也是回文字符串,这样回文字符串就能分解成一系列子问题了。
2.这样空间复杂度O(N^2),时间复杂度O(N^2)。
3.P[i][j]=0 表示子串i~j不是回文串,P[i][j]=1 表示子串i~j是回文串。
代码
精简版
public String longestPalindrome(String s) {
int n = s.length();
String res = null;
boolean[][] dp = new boolean[n][n];
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
if (dp[i][j] && (res == null || j - i + 1 > res.length())) {
res = s.substring(i, j + 1);
}
}
}
return res;
}
注释版
public class LongestPalindromicSubstring
{
public static String LongestPalindrome(String s)
{
if (s == null || s.length() == 1)
{
return s;
}
int len = s.length();
boolean[][] flags = new boolean[1000][1000]; //flags[i][j]=true表示字串i~j位回文字符串
int start = 0;
int maxlen = 0;
for (int i=0; i<len; i++)
{
flags [i][i] = true;
if (i<len-1 && s.charAt(i)==s.charAt(i+1)) //考虑相邻字符相同的情况
{
flags[i][i+1] = true;
start = i;
maxlen = 2;
}
}
for (int m = 3; m < len; m++) //i代表字符串长度,从3开始
{
for (int i = 0; i <=len-m; i++)
{
int j = i+m-1; //依次检查是否符合回文串条件
if (flags[i+1][j-1] && s.charAt(i)==s.charAt(j))
{
flags[i][j] = true;
start = i;
maxlen = m;
}
}
}
if (maxlen >= 2)
{
return s.substring(start, start+maxlen);
}
return null;
}
}