Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 55700 | Accepted: 23186 |
Description
Input
Output
Sample Input
abcfbc abfcab programming contest abcd mnp
Sample Output
4 2 0 解题思路:本题裸的最长公共子序列问题 经典dp 动态转移方程 1:char(a) == char(b) dp[i][j] = dp[i-1][j-1] +1; 2:char(a) != char(b) dp[i][j] = max(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])
在这里为新手提个醒 子序列可以不是连续的 子串才是必须连续的 我懵了好长时间。。。。。。源码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String a = scanner.next();
String b = scanner.next();
int [][] dp = new int [a.length()+1][b.length()+1];
for (int i = 1; i <= a.length(); i++) {
for (int j = 1; j <= b.length(); j++) {
if (a.charAt(i-1) == b.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] +1;
}else {
dp[i][j] = Math.max(Math.max(dp[i-1][j], dp[i][j-1]),dp[i-1][j-1]);
}
}
}
System.out.println(dp[a.length()][b.length()]);
}
}
}