Leetcode Longest Palindromic Substring


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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值