动态规划经典问题。
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();
}
}