这道题的HINT彻底把我弄糊涂了,结果WA5次才发现是求最大子序列而不是连续子串:
HINT
子序列的定义:字符串S中从S[ i ]...S[ j ]的长度为K的字符(i<=j),k<=j-i+1。
# include <stdio.h> # include <memory.h> # define MAX(x, y) ((x)>(y) ? (x):(y)) # define MAXN 1020 int len1, len2; char s1[MAXN], s2[MAXN]; short int f[MAXN][MAXN]; int main() { int i, j, max; while (~scanf("%d%s%d%s", &len1, s1+1, &len2, s2+1)) { max = 0; memset(f, 0, sizeof(f)); for ( i = 1; i <= len1; ++i) for ( j = 1; j <= len2; ++j) { if (s1[i] == s2[j]) f[i][j] = f[i-1][j-1]+1; else f[i][j] = MAX(f[i-1][j], f[i][j-1]); } printf("%d\n", f[len1][len2]); } return 0; }
不过也顺便复习了一下最大子串的方法,很相似, 都可以使用滚动数组。
# include <stdio.h> # include <memory.h> # include <ctype.h> # define MAXN 1020 int len1, len2; char s1[MAXN], s2[MAXN]; short int f[MAXN][MAXN]; int main() { int i, j, max;= while (~scanf("%d%s%d%s", &len1, s1+1, &len2, s2+1)) { max = 0; memset(f, 0, sizeof(f)); for ( i = 1; i <= len1; ++i) for ( j = 1; j <= len2; ++j) { if (tolower(s1[i]) == tolower(s2[j])) f[i][j] = f[i-1][j-1]+1; if (max < f[i][j]) max = f[i][j]; } printf("%d\n", max); } return 0; }