LeetCode -- 5. 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.

Example:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example:

Input: "cbbd"
Output: "bb"

算法思想:
这是一道动态规划题,当然也有更好的算法(著名的manacher(马拉车 :)算法),但是那个难度比较大,像我这样的弱菜第一次听说,基本给出动态规划的解法已经可以了。

定义bool数组d[i][j]为字符串从位置i到位置j是否为回文串。
初始状态:

d[i][j]=true,true,false,i=jj=i+1s[i]=s[j]otherwise

动态规划的状态转移方程( ji>=2 ):

d[i][j]={true,false,s[i]=s[j]d[i+1][j1]=trueotherwise


C++代码如下:

class Solution {
public:
    string longestPalindrome(string s) {
        const int strLen = s.size();
        int begin = 0,maxLen = 1;
        bool d[1000][1000] = {false};
        for(int i=0;i<strLen;i++)
        {
            d[i][i] = true;
        }
        for(int i = 0;i<strLen-1;i++)
        {
            if(s[i] == s[i+1])
            {
                d[i][i+1] = true;
                begin = i;
                maxLen = 2;
            }
        }
        for(int len = 3;len<=strLen;len++)
        {
            for(int i = 0;i< strLen-len+1;i++)
            {
                int j = i+len-1;
                if(s[i] == s[j] && d[i+1][j-1] == true)
                {
                    d[i][j] = true;
                    begin = i;
                    maxLen = len;
                }
            }
        }
        return s.substr(begin,maxLen);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值