基本思想:
后续总结,详见数据结构典型问题——动态规划篇;
#include<iostream> #include<stdlib.h> #include<stdio.h> #include<vector> #include<string> #include<math.h> #include<algorithm> #include<cstring> #include<map> #include<queue> #include<set> #include<stack> using namespace std; const int maxn = 1010; int dp[maxn][maxn]; int main() { string s; int ans = 1; getline(cin, s); int len = s.size(); //进行dp数组初始化; //单个字符可以构成一个回文子串; for (int i = 0; i < len; i++) { dp[i][i] = 1; } for (int i = 1; i < len; i++) { if (s[i] == s[i - 1]) { //如果相邻的两个字符可以构成回文子串; dp[i][i - 1] = dp[i - 1][i] = 1; ans = 2; } } //进行整体初始化; for (int l = 2; l < len; l++) { //直接加索引个数,不再看长度; for (int i = 0; i + l < len; i++) { if (s[i] == s[i + l]&&dp[i+1][i+l-1]==1) { dp[i][i + l] = dp[i + l][i] =1; ans = l + 1; } } } //cout << dp[0][len - 1] << endl;; cout << ans << endl; return 0; }