-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.最长回文子串.cpp
64 lines (57 loc) · 1014 Bytes
/
5.最长回文子串.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @lc app=leetcode.cn id=5 lang=cpp
*
* [5] 最长回文子串
*/
#include <bits/stdc++.h>
using namespace std;
// @lc code=start
class Solution
{
public:
string longestPalindrome(string s)
{
int len = s.length();
if (s.length() == 1)
{
return s;
}
int maxL = 1;
int theL = 0;
vector<vector<bool>> dp(len, vector<bool>(len, false));
for (int i = 0; i < len; i++)
{
dp[i][i] = true;
}
for (int L = 2; L <= len; L++)
{
for (int l = 0; l < len; l++)
{
int r = l + L - 1;
if (r >= len)
{
break;
}
if (s[l] != s[r])
{
dp[l][r] = false;
}
else if (r - l + 1<= 2)
{
dp[l][r] = true;
}
else
{
dp[l][r] = dp[l + 1][r - 1];
}
if (dp[l][r] && L > maxL)
{
maxL = L;
theL = l;
}
}
}
return s.substr(theL, maxL);
}
};
// @lc code=end