1.动态规划法,参考官方题解
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
int dp[n][n];
string ans;
for (int L = 0; L < n; ++l) {
for (int i = 0; i + L < n; ++i) {
int j = i + L;
if (L == 0) {
dp[i][j] = 1;
} else if (l == 1) {
dp[i][j] = (s[i] == s[j]);
} else {
dp[i][j] = (s[i] == s[j] && dp[i + 1][j - 1]);
}
if (dp[i][j] && L + 1 > ans.size()) {
ans = s.substr(i, L + 1);
}
}
}
return ans;
}
};