5. Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/
/*
* @lc app=leetcode id=5 lang=cpp
*
* [5] Longest Palindromic Substring
*/
class Solution {
public:
string longestPalindrome(string s) {
const int N = s.size();
if (N == 0) return s;
int r = 1;
vector<vector<bool>> dp(N, vector<bool>(N));
for (int i = 0; i < N; ++i) dp[i][i] = true;
string res(1, s[0]);
for (int i = N - 2; i >= 0; --i) {
for (int j = i + 1; j < N; ++j) {
if (s[i] == s[j] && (j == i + 1 || dp[i + 1][j - 1])) {
dp[i][j] = true;
const auto len = j - i + 1;
if (len > r) {
r = len;
res = s.substr(i, len);
}
}
}
}
return res;
}
};
Last updated