Given a string
S
, find the longest palindromic substring in
S
. You may assume that the maximum length of
S
is 1000, and there exists one unique longest palindromic substring.
字符串长度为N,一共有N^2种子字符串的可能,检测每一种子字符串的时间复杂度都是N,这样就是N^3的复杂度。太贵不考虑。
换个思路。检查每个子字符串是否回文可以依靠他掐头去尾的子字符串的信息。用二维数组isPalindrome[i][j] (0 < i < j < N-1)表示第i个字符到第j个字符所构成的字串是否是回文。很明显isPalindrome[i][i] = true,isPalindrome[i][i+1] = str[i]==str[i+1],一般情况isPalindrome[i][j]=isPalindrome[i+1][j-1]&&str[i]==str[j]。构造一个这样的二维数组,然后遍历数组找到值为真的i和j取差取最大即可。
上代码
public class Solution {
public String longestPalindrome(String s) {
if(s==null || s.length()==0 ) return "";
int n = s.length();
boolean[][] isPalindrome = new boolean[n][n];
for(int i=0;i<n;i++){
isPalindrome[i][i] = true;
if(i<n-1){
isPalindrome[i][i+1] = s.charAt(i)==s.charAt(i+1);
}
}
for(int i=n-1;i>=0;i--){
for(int j = i+2; j<n; j++){
isPalindrome[i][j] = isPalindrome[i+1][j-1] && s.charAt(i)==s.charAt(j);
}
}
int len = 0;
String res="";
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(isPalindrome[i][j]){
len = Math.max(len, j-i+1);
if(len==j-i+1) res = s.substring(i,j+1);
}
}
}
return res;
}
}
时间空间复杂度都是O(N^2)