You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
LCS is the problem of finding longest common subsequence that is present in given two seqeunces in the SAME ORDER.
6
+
ie. Find the longest seqeunce which can be obtained from the first original sequence by DELETING some items and from the second original sequence by deleting other items.
7
+
example -
8
+
X : ABCBDAB
9
+
Y : BDCABA
10
+
Length of LCS is 4. LCS are BDAB, BCAB, BCBA
11
+
NAIVE APPROACH
12
+
check if all subsequence of X[1...n] are also a subsequence of Y[1...m].
13
+
Number of subsequences of length 1 = nC1
14
+
Number of subsequences of length 2 = nC2
15
+
.
16
+
.
17
+
.
18
+
Number of subsequences of length n = nCn
19
+
We know, nC0 + nC1 + .... + nCn = 2^n
20
+
number of subsquences of length ATLEAST 1 AND ATMOST n = (2^n)-1
21
+
Time required of check if a subsequence is also a subsequence of Y = m
Other redundant recursive calls take constant time
79
+
Space Complexity - O(n*m)
80
+
*/
81
+
82
+
//BOTTOM-UP APPROACH
83
+
/*Calculate smaller value first and work towards the bigger problem.*/
84
+
classLCS{
85
+
publicintLCSlength(Stringa, Stringb, intn, intm){
86
+
intlcs[][] = newint[n+1][m+1];
87
+
88
+
//first column of all rows is 0
89
+
for(inti=0;i<=n;i++) lcs[i][0] = 0;
90
+
//first row of all coumns is 0
91
+
for(intj=0;j<=m;j++) lcs[0][j] = 0;
92
+
93
+
for(inti=1;i<=n;i++){
94
+
for(intj=1;j<=m;j++){
95
+
/*
96
+
when a[i]==b[j], we can simply look for the last answer and add one to it.
97
+
One is added to reflect that the current pair of characters are a match.
98
+
last answer is found by not considering the current elements ie. going to the upper dioagnal cell
99
+
*/
100
+
if(a.charAt(i-1)==b.charAt(j-1)){
101
+
lcs[i][j] = lcs[i-1][j-1]+1;
102
+
}
103
+
104
+
/*
105
+
when a[i]!=b[j],
106
+
We can discard one character at a time from both the sequence to see if there is a match or not.
107
+
let us assume,
108
+
Sequence after dropping the last character = oldSeq
109
+
Sequence kept as it is ie. Sequence which includes the current character = newSeq
110
+
111
+
Since we have added a new character in the newSeq, there is a possibilty that the last character of oldSeq matches the newly added last char of newSeq.
112
+
*/
113
+
else{
114
+
lcs[i][j] = Math.max(lcs[i-1][j], lcs[i][j-1]);
115
+
}
116
+
}
117
+
}
118
+
119
+
returnlcs[n][m];
120
+
}
121
+
}
122
+
/*
123
+
Time Complexity -
124
+
We are computing each of the (n*m) subproblems = O(n*m)
0 commit comments