最长回文子串 动态规划:最长回文子串 //动规,时间复杂度O(n^2),空间复杂度O(n^2) string solution(string s) { const int n = s.size(); bool **f = new bool*[n]; for (int i = 0; i < n; ++i) { f[i] = new bool[n]; fill_n(f[i], n, false); } //用vector会超时 //vector<vector<bool>> f(n, vector<bool>(n, false)); size_t max_len = 1, start = 0; //最长回文子串的长度,起点 for ( size_t i = 0; i < n; ++i ) { f[i][i] = true; for ( size_t j = 0; j < i; ++j ) { f[j][i] = (s[j] == s[i] && ( i - j < 2 || f[j + 1][i - 1]) ); if (f[j][i] && max_len < (i - j + 1)) { max_len = i - j + 1; start = j; } } } for (int i = 0; i < n; ++i) { delete [] f[i]; } delete [] f; return s.substr(start, max_len); }