手写代码:查找最长回文子串
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<cmath> using namespace std; const int MAXN = 1010; int dp[MAXN][MAXN]; int main() { string str; cin >> str; int len = str.length(); int maxLen = 1; //最长回文字子串的长度 memset(dp, 0, sizeof(dp)); //dp数组初始化为0 //边界 for(int i = 0; i < len; i++){ dp[i][i] = 1; if(i < len - 1){ if(str[i] == str[i + 1]){ //如果str[i] = str[i+1],则更新maxLen dp[i][i + 1] = 1; maxLen = 2; } } } //状态转移方程 for(int L = 3; L <= len; L++){ //枚举子串的长度,从3开始,因为上面的语句已经把长度为1和2的子串都枚举完毕 for(int j = 0; j + L - 1 < len; j++){ //枚举子串的起点 int i = j + L - 1; //子串的右端点 if(str[j] == str[i] && dp[j + 1][i - 1] == 1){ dp[j][i] = 1; maxLen = L; //更新maxLen } } } printf("%d", maxLen); return 0; }