Jobdu-1042.Coincidence

LCS – Longest Common Subsequence

Question

题目描述:

Find a longest common subsequence of two strings.

输入:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出:

For each case, output k – the length of a longest common subsequence in one line.

样例输入:

abcdcxbydz

样例输出:

2

来源:

2008年上海交通大学计算机研究生机试真题

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String a = sc.next();
String b = sc.next();
int m = a.length(), n = b.length();
int[][] dp = new int[m+1][n+1];
for(int i = 0; i <= m; i++)
dp[i][0] = 0;
for(int j = 0; j <= n; j++)
dp[0][j] = 0;
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(a.charAt(i-1) == b.charAt(j-1))
dp[i][j] = dp[i-1][j-1] + 1;
else if(a.charAt(i-1) != b.charAt(j-1))
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
System.out.println(dp[m][n]);
}
}
}

Time complexity: $O(n^2)$