题解 | #最长公共子序列(一)#
最长公共子序列(一)
http://www.nowcoder.com/practice/672ab5e541c64e4b9d11f66011059498
Java: 这里使用了char数组,也可以不用char数组,直接用String类的charAt()方法获取单个字符。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String nums = scanner.nextLine();
String s1 = scanner.nextLine();
String s2 = scanner.nextLine();
// 开始算法
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int[][] dp = new int[c1.length+1][c2.length+1];
for (int i = 1; i <= c1.length; i++) {
for (int j = 1; j <= c2.length; j++) {
if (c1[i-1] == c2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
}
}
}
System.out.println(dp[c1.length][c2.length]);
}
}