动态规划经典问题。
f[i][j] 表示第一个序列的前i个字母,第二个序列的前j个字母构成的公共子序列。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 1010;
static int n, m;
static char[] a = new char[N], b = new char[N];
static int f[][] = new int[N][N];
public static void main(String[] args) throws IOException {
String[] s = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
a = br.readLine().toCharArray();
b = br.readLine().toCharArray();
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
if (a[i - 1] == b[j - 1]) f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + 1);
}
pw.println(f[n][m]);
pw.flush();
pw.close();
br.close();
}
}
本文介绍了一个使用动态规划解决最长公共子序列问题的经典算法实现。通过二维数组f[i][j]记录两个序列的前i和前j个字符构成的最长公共子序列长度,最终输出的是两个序列的最长公共子序列长度。
1189

被折叠的 条评论
为什么被折叠?



