-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_173LCS.java
More file actions
58 lines (58 loc) · 1.89 KB
/
_173LCS.java
File metadata and controls
58 lines (58 loc) · 1.89 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
import java.util.*;
public class _173LCS {
public static int lcs(String str1,String str2,int n,int m){
if(m==0 || n==0){
return 0;
}
if(str1.charAt(n-1)==str2.charAt(m-1)){
return lcs(str1,str2,n-1,m-1)+1;
} else{
int ans1 = lcs(str1,str2,n-1,m);
int ans2 = lcs(str1,str2,n,m-1);
return Math.max(ans1,ans2);
}
}
public static int lcsmemo(String str1,String str2,int n,int m){
int dp[][] =new int[n+1][m+1];
for(int i=0;i<dp.length;i++){
for(int j=0;j<dp[0].length;j++){
dp[i][j]=-1;
}
}
if(m==0 || n==0){
return 0;
}
if(dp[n][m]!=-1){
return dp[n][m];
}
if(str1.charAt(n-1)==str2.charAt(m-1)){
return dp[n][m]=lcsmemo(str1,str2,n-1,m-1)+1;
} else{
int ans1 = lcsmemo(str1,str2,n-1,m);
int ans2 = lcsmemo(str1,str2,n,m-1);
return dp[n][m]= Math.max(ans1,ans2);
}
}
public static int lcsTab(String str1,String str2,int n,int m){
int dp[][] =new int[n+1][m+1];
for(int i =1;i<n+1;i++){
for(int j = 1;j<m+1;j++){
if(str1.charAt(i-1)==str2.charAt(j-1)){
dp[i][j]=dp[i-1][j-1]+1;
} else{
int ans1 = dp[i-1][j];
int ans2 = dp[i][j-1];
dp[i][j]=Math.max(ans1,ans2);
}
}
}
return dp[n][m];
}
public static void main(String[] args) {
String str1 = "abcdge";
String str2 = "abedg";
//System.out.println(lcs(str1, str2, str1.length(),str2.length()));
// System.out.println(lcsmemo(str1, str2, str1.length(),str2.length()));
System.out.println(lcsTab(str1, str2, str1.length(),str2.length()));
}
}