解法一:动态规划
dp[i][j]
表示 Python
风格的子串 str[i:j+1]
是否为回文串。
#include <bits/stdc++.h>
using namespace std;
// dp[i][j]表示Python风格的子串str[i:j+1]是否为回文串
bool dp[1005][1005];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string str;
getline(cin, str);
int ans = 1;
int len = str.size();
for (int i = 0; i < len; ++i) {
dp[i][i] = true;
if (i < len - 1 && str[i] == str[i + 1]) {
dp[i][i + 1] = true;
ans = 2;
}
}
for (int l = 3; l <= len; ++l) {
for (int i = 0, j = i + l - 1; j < len; ++i, ++j) {
if (str[i] == str[j] && dp[i + 1][j - 1]) {
dp[i][j] = true;
ans = l;
}
}
}
cout << ans << '\n';
}