LeetCode-5. Longest Palindromic Substring

241 篇文章 1 订阅
210 篇文章 0 订阅

5. Longest Palindromic Substring

Medium

4380400FavoriteShare

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

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

Example 2:

Input: "cbbd"
Output: "bb"

 

这题的状态转移方程实在是没想明白,看来好久解析才看懂,附上博主原文地址

先附上作者原文地址:https://blog.csdn.net/small__snail__5/article/details/80310615

 

#include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;


class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length();
        int **dp = new int*[len+1];
        for(int i=0;i<len+1;i++){
            dp[i] = new int[len+1];
        }
        for(int i=0;i<len+1;i++){
            for(int j=0;j<len+1;j++){
                dp[i][j] = 0;
            }
        }

        /* j+1 > j+i-1 ----> 即当i<2的时候才有可能满足 j+1 > j+i-1*/
        for(int j=0;j<len;j++){
            dp[j][j] = 1;
            dp[j+1][j] = 1;
        }

        int left=0,right=0;
        for(int i=1;i<len;i++){
            for(int j=0;j+i<len;j++){
                if(s[j]==s[j+i] && dp[j+1][j+i-1]==1){
                    left = j;
                    right = j+i;
                    dp[left][right] = 1;
                }
            }
        }

        int res_len = right - left + 1;
        string res = s.substr(left, res_len);
        return res;
    }
};


int main(){

    string str = "cbbd";
    Solution *ps = new Solution();
    string res = ps->longestPalindrome(str);
    cout<<res<<endl;

    system("pause");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值