5. Longest Palindromic Substring 题解

本文介绍了一种利用动态规划求解最长回文子串的方法,通过避免重复计算提高效率。文中详细阐述了状态转移方程及边界条件,并给出了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

  • Total Accepted: 202411
  • Total Submissions: 805973
  • Difficulty: Medium
  • Contributor: LeetCode

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"
动态规划方法:
我们要知道如何避免不必要的重新计算,验证回文。如果我们已经知道的'bab”''bab”是回文,那么可知,“'ababa”''ababa”必是回文,因为左右两端字母是一样的。
定义p(i,j)p(i,j)如下:
P(i,j)={true,if the substring Si…Sj is a palindromefalse,otherwise. P(i,j)={true,if the substring Si…Sj is a palindromefalse,otherwise. 
因此,
P(i, j) = ( P(i+1, j-1) \text{ and } S_i == S_j )P(i,j)=(P(i+1,j−1) and S​i​​==S​j​​)
基本情况如下:
P(i, i) = trueP(i,i)=true
P(i, i+1) = ( S_i == S_{i+1} )P(i,i+1)=(S​i​​==S​i+1​​)
复杂度分析
.Time complexity : O(n^2)O(n​2​​). This gives us a runtime complexity of O(n^2)O(n​2​​).
.Space complexity : O(n^2)O(n​2​​). It uses O(n^2)O(n​2​​) space to store the table.
这是以abade为例,得到的dp矩阵:
给出代码:
public String longestPalindrome(String s) {
    boolean[][] flag = new boolean[s.length()][s.length()];
    int maxlen = 0,start = 0;
    for(int i = 0;i < s.length(); i++){
        flag[i][i] = true;
        maxlen = 1;
        start = i;
    }
    for(int i = 0;i < s.length()-1; i++)
        if(s.charAt(i)==s.charAt(i+1)){
            flag[i][i+1] = true;
            maxlen = 2;
            start = i;
        }
    for(int len = 3; len<= s.length(); len++)
        for(int i = 0;i < s.length()-len+1; i++){
            int j = i+len-1;
            if(s.charAt(i)==s.charAt(j)&&flag[i+1][j-1]==true){
                flag[i][j] = true;
                maxlen = len;
                start = i;
            }
        }
    return s.substring(start, start+maxlen);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值