力扣5 最长回文子串
程序员文章站
2022-07-13 17:36:00
...
// leetcode.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include<vector>
#include<string>
#include<iostream>
using namespace std;
#define max(a,b) (((a)>(b))? (a):(b))
#define min(a,b) (((a)<(b))? (a):(b))
class Solution {
public:
string longestPalindrome(string s)
{
int len = s.size();
if (len == 0 || len == 1)
return s;
int cur_len = 0;
int max_len = 1;
int start = 0;
vector<vector<bool>>dp(len,vector<bool>(len));//二维动态数组的初始化要注意
for (int l = 0; l < len; l++)
{
for (int r = 0; r < len; r++)
{
if (l == r)
{
dp[l][r] = true;
}
else
{
dp[l][r] = false;
}
}
}
for (int r = 1; r < len; r++)
{
for (int l=0; l < r; l++)
{
if (s[l] == s[r])
{
if (r - l < 3)
{
dp[l][r] = true;
}
else
{
dp[l][r] = dp[l + 1][r - 1];
}
}
else
{
dp[l][r] = false;
}
if (dp[l][r])
{
cur_len = r - l + 1;
if (cur_len > max_len)
{
max_len = cur_len;
start = l;
}
}
}
}
return s.substr(start, max_len);
}
};
int main(int argc, char *argv[])
{
Solution solution;
string ret = solution.longestPalindrome("cbbd");
cout << ret;
return 0;
}
vector<vector<bool>>dp(len,vector(len));//二维动态数组的初始化要注意
因为一个二维向量vector<vector >,初始只能确定列数,但是无法确定行数
所以需要明确说明行数
一般有下列俩中初始化方法
上一篇: 程序员是怎么记住一堆密码的?
下一篇: 黄金点游戏开发(三)