力扣5. 最长回文子串

Problem: 5. 最长回文子串

题目描述

>

思路

1.状态定义:dp[i][j]表示s[i…j]是回文字符串(定义为bool类型若为true则表示是回文串);
2.状态初始化:所有长度为0的均为回文串,即dp[i][i] == true;
3.状态转移:若s[i] != s[j],则dp[i][j] == false,若s[i] = s[j],则dp[i][j] = dp[i + 1][j - 1]

复杂度

时间复杂度:

O ( N 2 ) O(N^2) O(N2);其中 N N N为字符串的长度

空间复杂度:

O ( N 2 ) O(N^2) O(N2)

Code

class Solution {
    /**
     * Longest Palindromic Substring
     *
     * @param s Given string
     * @return String
     */
    public String longestPalindrome(String s) {
        int len = s.length();
        if (len < 2) {
            return s;
        }
        int maxLen = 1;
        int begin = 0;
        // dp[i][j] Indicates whether s[i..j] is a palindrome string
        boolean[][] dp = new boolean[len][len];
        // dp[i][j] Indicates whether s[i..j] is a palindrome string
        for (int i = 0; i < len; ++i) {
            dp[i][i] = true;
        }
        for (int L = 2; L <= len; ++L) {
            for (int l = 0; l < len; ++l) {
                // L and l can determine the right boundary, that is, r - l + 1 = L
                int r = L + l - 1;
                // If the right boundary is out of bounds, you can exit the current loop
                if (r >= len) {
                    break;
                }
                if (s.charAt(l) != s.charAt(r)) {
                    dp[l][r] = false;
                } else {
                    if (r - l < 3) {
                        dp[l][r] = true;
                    } else {
                        dp[l][r] = dp[l + 1][r - 1];
                    }
                }
                // As long as dp[i][L] == true is true, it means that
                // the substring s[i..L] is a palindrome,
                // in which case the palindrome length and starting position are recorded
                if (dp[l][r] && r - l + 1 >= maxLen) {
                    maxLen = r - l + 1;
                    begin = l;
                }
            }
        }
        return s.substring(begin, begin + maxLen);
    }
}
  • 11
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值