-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS.java
More file actions
67 lines (54 loc) · 1.7 KB
/
LCS.java
File metadata and controls
67 lines (54 loc) · 1.7 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.*;
import java.util.Arrays;
public class LCS {
static int dp[][]=new int[7][7];
static int lcs(String x, String y, int n, int m){
if(n==0 || m==0){
return 0;
}
if(dp[n][m]!=-1){
return dp[n][m];
}
if(x.charAt(n-1) == y.charAt(m-1)){
dp[n][m] = 1 + lcs(x.substring(0,n-1), y.substring(0,m-1), n-1, m-1);
return dp[n][m];
}
else{
dp[n][m] = Math.max(lcs(x.substring(0,n-1), y.substring(0,m), n-1, m),
lcs(x.substring(0,n), y.substring(0,m-1), n, m-1)) ;
return dp[n][m];
}
}
public static void main(String[] args){
int t[][] = new int[7][7];
// for(int[] row:dp)
// Arrays.fill(row, -1);
String s1 = "abcdgh";
String s2 ="abedfh";
// lcs(s1, s2, s1.length(), s2.length());
for(int i= 0; i<7;i++){
for(int j=0; j<7; j++){
if(i==0||j==0){
t[i][j] = 0;
}
}
}
for(int i= 1; i<7; i++){
for(int j=1; j<7; j++){
if(s1.charAt(i-1) == s2.charAt(j-1)){
t[i][j] = 1 + t[i-1][j-1];
}
else{
t[i][j] = Math.max(t[i-1][j], t[i][j-1]);
}
}
}
// System.out.println(lcs(s1, s2, s1.length(), s2.length()));
for(int i =0; i<7;i++){
for(int j= 0; j<7;j++){
System.out.print(t[i][j] +" ");
}
System.out.println();
}
}
}