uva 11151(dp)

来源:互联网 发布:数据库考试题库 编辑:程序博客网 时间:2024/06/08 14:50

题意:给出一个字符串,要求输出字符串中的最长的回文子串的长度。

题解:递归dp,f[i][j]代表从i到j的字符串内最长回文串长度。


#include <stdio.h>#include <string.h>const int N = 1000;char str[N];int f[N][N];int dp(int l, int r) {if (f[l][r] != -1)return f[l][r];if (l > r)return 0;if (l == r)return 1;if (str[l] == str[r])return f[l][r] = dp(l + 1, r - 1) + 2;else {int temp1 = dp(l + 1, r);int temp2 = dp(l, r - 1);f[l][r] = temp1 > temp2 ? temp1 : temp2;return f[l][r];}}int main() {int t;scanf("%d", &t);getchar();while (t--) {memset(f, -1, sizeof(f));gets(str);int len = strlen(str);printf("%d\n", dp(0, len - 1));}return 0;}

网上看到的其他做法,把字符当做中间字符,然后向两边扩展,要先找相同,这是为了先能找到找偶数回文,再找奇数回文。

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int N = 1000005;char str[N];int solve() {int res = 0, len = strlen(str);for (int i = 1; str[i]; i++) {int s = i, e = i;while (str[s] == str[e + 1])e++;i = e;while (str[s - 1] == str[e + 1]) {s--;e++;}res = max(res, e - s + 1);}return res;}int main() {str[0] = '$';int t;scanf("%d", &t);while (t--) {scanf("%s", str + 1);printf("%d\n", solve());}return 0;}


0 0
原创粉丝点击