-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.最长回文子串.cpp
50 lines (47 loc) · 1.13 KB
/
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
/*
* @lc app=leetcode.cn id=5 lang=cpp
*
* [5] 最长回文子串
*/
// @lc code=start
class Solution
{
public:
string longestPalindrome(string s)
{
const int len = s.length();
std::string res;
if (s.empty())
return 0;
int sublen = 1;
std::vector<std::vector<bool>> dp(len, std::vector<bool>(len, false));
for (auto i = 0; i < len; i++)
{
for (auto j = 0; j <= i; j++)
{
if (j == i)
{
dp[j][i] = true;
}
else if (i == j + 1)
{
dp[j][i] = (s[i] == s[j]);
}
else
{
dp[j][i] = (s[i] == s[j] && dp[j + 1][i - 1] == true);
}
if (dp[j][i])
{
if (i - j + 1 >= sublen)
{
sublen = i - j + 1;
res = s.substr(j, i - j + 1);
}
}
}
}
return res;
}
};
// @lc code=end