LeetCode之最长回文子串

1.题目链接

5. 最长回文子串 - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/longest-palindromic-substring/description/

 

2.题目解析

对于这道题目我们可以使用动态规划的思路来求解,具体思路是,对于一个长度大于2的子串,如果它是回文串的话,那么将它首尾的两个字母去除之后,它仍然是个回文串。例如对于“ababa”,将首尾字符串去掉,剩下的还是回文串,那么我们就可以列出下面状态转移方程:

当子串长度大于2时

f[i][j] = f[i+1][j-1]\wedge s[i]==s[j]

当子串长度等于2时

f[i][j]=(s[i]==s[j])

 

3.代码如下:

class Solution {
public:
    string longestPalindrome(string s) {
        int n=s.size();

        bool f[n][n];

        memset(f,false,sizeof f);

        int maxi=0;

        string res;

        for(int l=1;l<=n;l++)
        {
            for(int i=0;i+l-1<n;i++)
            {
                int j=i+l-1;
                if(s[i]==s[j])
                {
                    if(j-i<3)
                    {
                        f[i][j]=true;
                    }
                    else if(f[i+1][j-1])
                    f[i][j]=true;

                    if(f[i][j]&&l>=maxi)
                    {
                        maxi=l;
                        res=s.substr(i,l);
                    }
                }
            }
        }
    
        return res;
    }
};

相关推荐

  1. Leetcode

    2024-07-17 00:48:02       21 阅读
  2. LeetCode-5

    2024-07-17 00:48:02       49 阅读
  3. 【Manacher】LeetCode-5.

    2024-07-17 00:48:02       48 阅读
  4. LeetCode_5_中等_

    2024-07-17 00:48:02       52 阅读
  5. leetcode 5.

    2024-07-17 00:48:02       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 00:48:02       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 00:48:02       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 00:48:02       62 阅读
  4. Python语言-面向对象

    2024-07-17 00:48:02       72 阅读

热门阅读

  1. Git 的基本概念和使用方式

    2024-07-17 00:48:02       27 阅读
  2. 常见的SQL MODE及其解释

    2024-07-17 00:48:02       23 阅读
  3. [C++]类作用域

    2024-07-17 00:48:02       23 阅读
  4. 入门C语言只需一个星期(星期一)

    2024-07-17 00:48:02       28 阅读
  5. 算法-双指针

    2024-07-17 00:48:02       22 阅读
  6. Mybatis 之批量处理

    2024-07-17 00:48:02       21 阅读
  7. Spring Boot 面试题及答案整理,最新面试题

    2024-07-17 00:48:02       22 阅读
  8. 【python基础】学习路线

    2024-07-17 00:48:02       21 阅读