解法一:动态规划

dp[i][j] 表示 Python 风格的子串 str[i:j+1] 是否为回文串。
1040 Longest Symmetric String - 图1

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. // dp[i][j]表示Python风格的子串str[i:j+1]是否为回文串
  4. bool dp[1005][1005];
  5. int main() {
  6. ios::sync_with_stdio(false);
  7. cin.tie(0);
  8. string str;
  9. getline(cin, str);
  10. int ans = 1;
  11. int len = str.size();
  12. for (int i = 0; i < len; ++i) {
  13. dp[i][i] = true;
  14. if (i < len - 1 && str[i] == str[i + 1]) {
  15. dp[i][i + 1] = true;
  16. ans = 2;
  17. }
  18. }
  19. for (int l = 3; l <= len; ++l) {
  20. for (int i = 0, j = i + l - 1; j < len; ++i, ++j) {
  21. if (str[i] == str[j] && dp[i + 1][j - 1]) {
  22. dp[i][j] = true;
  23. ans = l;
  24. }
  25. }
  26. }
  27. cout << ans << '\n';
  28. }