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
| class Solution { public: string longestPalindrome(string s) { int n = s.size(); int maximum = 1, maxI = 0, maxJ = 0; vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { if (i == j) { dp[i][j] = 1; } else { dp[i][j] = max(dp[i][j - 1], dp[i + 1][j]); if (dp[i + 1][j - 1] == j - i - 1 && s[i] == s[j]) dp[i][j] = max(dp[i][j], dp[i + 1][j - 1] + 2); } if (dp[i][j] > maximum) { maximum = dp[i][j]; maxI = i; maxJ = j; } } } return string(s.begin() + maxI, s.begin() + maxJ + 1); } };
|