Leetcode 5.最长回文子串

56 阅读1分钟

题目描述

给你一个字符串 s,找到 s 中最长的回文子串。

如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。

示例 1:

输入: s = "babad"
输出: "bab"
解释: "aba" 同样是符合题意的答案。

示例 2:

输入: s = "cbbd"
输出: "bb"

 

提示:

  • 1 <= s.length <= 1000
  • s 仅由数字和英文字母组成

Tips:

  • 假设n是字符串长度,构建dp[n][n],dp[i][j]只等于0或者1,如果dp[i][j]=0,代表从i到j的子串不是回文子串;如果dp[i][j]=1,代表从i到j的子串是回文子串;
  • 状态转移方程:if(s[i]=s[j]) dp[i][j]=dp[i+1][j-1]
  • 将对角线和次对角线初始化

5a2ebe131b08ff4febcdd9de1e0b667.jpg

Code

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s;
    cin>>s;

    int n=s.length();
    int dp[107][107]={0};
    //初始化对角线
    for(int i=0;i<n;i++)dp[i][i]=1;
    int ans=1;
    int l=0,r=0;
    //初始化次对角线
    for(int i=1;i<n;i++){
        int j=i-1;
        string tmp=s.substr(j,2);
        string tmp1=tmp;
        reverse(tmp.begin(),tmp.end());
        if(tmp==tmp1){
            dp[i][j]=1;
        }else{
            dp[i][j]=0;
        }
    }
    //状态转移过程
    for(int k=1;k<n;k++){
        for(int i=0;i<n-k;i++){
            int j=i+k;
            if(s[i]==s[j]){
                //cout<<i<<" -- "<<j<<endl;
                dp[i][j]=dp[i+1][j-1];
                if(dp[i][j]&&(j-i+1)>ans){
                    ans=j-i+1;
                    l=i;
                    r=j;
                }
            }
        } 
    }
    // for(int i=0;i<n;i++){
    //     for(int j=0;j<n;j++){
    //         cout<<dp[i][j]<<" ";
    //     }cout<<endl;
    // }
    cout<<s.substr(l,r-l+1)<<endl;


}