题目链接:http://poj.org/problem?id=2955
题意:求回文子串的最大长度。
解法:枚举区间长度,更新答案。
代码:
#include <stdio.h>
#include <ctime>
#include <math.h>
#include <limits.h>
#include <complex>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <bitset>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <time.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
using namespace std;
char s[110];
int dp[110][110];
int main()
{
while (scanf("%s", s+1) != EOF)
{
memset(dp,0,sizeof(dp));
if (strcmp(s+1, "end") == 0) break;
int n = strlen(s + 1);
for (int i = 1; i < n; i++)
{
if ((s[i] == ‘(‘ && s[i + 1] == ‘)‘) || (s[i] == ‘[‘ && s[i + 1] == ‘]‘))
dp[i][i + 1] = 2;
}
for (int k = 2; k <= n-1; k++)
{
for (int i = 1; i + k <= n; i++)
{
if ((s[i] == ‘(‘ && s[i + k] == ‘)‘) || (s[i] == ‘[‘ && s[i + k] == ‘]‘))
dp[i][i + k] = dp[i + 1][i + k - 1] + 2;
for (int j = i; j <= i + k;j++)
dp[i][i + k] = max(dp[i][i+k],dp[i][j] + dp[j][i+k]);
}
}
printf("%d\n",dp[1][n]);
}
return 0;
}
时间: 2024-10-10 10:19:22