-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS2.java
More file actions
45 lines (39 loc) · 1.22 KB
/
Copy pathLCS2.java
File metadata and controls
45 lines (39 loc) · 1.22 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
StringBuffer lcs = new StringBuffer();
int[][] dp = new int[str1.length()+1][str2.length()+1];
for(int i=1; i<str1.length()+1; i++){
for(int j=1; j<str2.length()+1; j++){
if(str1.charAt(i-1)==str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1]+1;
}else{
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
int i = str1.length();
int j = str2.length();
while(true){
if(i==0||j==0) break;
if(dp[i][j]==dp[i-1][j]) {
i--;
}
else if(dp[i][j]==dp[i][j-1]) {
j--;
}
else {
lcs.append(str1.charAt(i-1));
i--;
j--;
}
}
System.out.println(dp[str1.length()][str2.length()]);
if(dp[str1.length()][str2.length()]!=0){
System.out.println(lcs.reverse());
}
}
}