题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { // 最长连续回文串 string str; while(getline(cin, str)) { int n = str.size(); vector<vector<int>> dp(n, vector<int>(n,0)); int ans = 0; for (int i = 0; i < n; i++) dp[i][i] = 1; for (int len = 2; len <= n; len++) { for (int i = 0; i <= n-len; i++) { if (len == 2) { dp[i][i+1] = str[i] == str[i+len-1] ? len:0; } else { if (str[i] == str[i+len-1]) { if (dp[i+1][i+len-2] > 0) dp[i][i+len-1] = dp[i+1][i+len-2]+2; } } ans = max(ans, dp[i][i+len-1]); // cout << i << "," << i+len-1 << ":" << dp[i][i+len-1] << endl; } } cout << ans << endl; } } // 64 位输出请用 printf("%lld")
动态规划,求最长连续回文串
需要注意的是,
第一层for循环变量是字串的长度,从2到n
第二层for循环是字串起始位置,从0到n-len