-
Notifications
You must be signed in to change notification settings - Fork 3
/
lcs_topDown.java
41 lines (26 loc) · 965 Bytes
/
lcs_topDown.java
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
public class lcs_topDown {
public int longestCommonSubsequence(String text1, String text2) {
int n = text1.length();
int m = text2.length();
int[][] dp = new int[1001][1001];
// initialisation as the base condition in recursive solution
for(int i = 0 ; i < n+1 ; i++){
for(int j = 0 ; j < m + 1 ; j++){
if(i == 0 || j == 0){
dp[i][j] = 0;
}
}
}
for(int i = 1 ; i < n+1 ; i++){
for(int j = 1 ; j < m +1 ; j++){
if(text1.charAt(i-1) == text2.charAt(j-1)){
dp[i][j] = 1 + dp[i-1][j-1];
}
else{
dp[i][j] = Math.max(dp[i][j-1] , dp[i-1][j]);
}
}
}
return dp[n][m];
}
}