- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathLongestCommonSubsequence.java
More file actions
Latest commit
65 lines (58 loc) · 3.01 KB
/
Copy pathLongestCommonSubsequence.java
File metadata and controls
65 lines (58 loc) · 3.01 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
// LongestCommonSubsequence
// Approach for solvering the Problem
// 1. Create a 2D array “dp” with rows and columns equal to the length of each input string plus 1.
// 2. Initialize the first row and column of the dp array to 0.
// 3. Iterate through the rows of the dp array, starting from 1.
// 4. Within the outer loop, iterate through the columns of the dp array, also starting from 1.
// 5. If the character at the current row of the first input string is equal to the character at the current column of the second input string, set the current element of the dp array to the
// value of the element above-left of the current element, plus 1.
// 6. Else, set the current element of the dp array to the maximum value of the element above or to the left of the current element.
// 7. After the nested loops, the last element of the dp array will contain the length of the LCS.
// 8. To find the actual LCS, initialize an empty string and iterate through the dp array, starting from the last element and going towards the first element.
// 9. At each step, if the current element is not equal to the element above or to the left of it,
// add the character at the current position of the corresponding input string to the LCS string and move diagonally to the left and up.
// 10.Else, move either up or left, whichever element is greater.
// 11.Reverse the LCS string to get the final result.
packageJava_practice.Dynamic_Programming;
importjava.util.*;
importjava.lang.*;
importjava.io.*;
classLongestCommonSubsequence {
publicstaticvoidmain (String[] args) {
Scannersc=newScanner(System.in);
inttest=sc.nextInt();
while(test-- > 0){
intp=sc.nextInt(); // Take size of both the strings as input
intq=sc.nextInt();
Strings1=sc.next(); // Take both the string as input
Strings2=sc.next();
publicstaticintlcss(intm,intn,Strings1,Strings2,intdp[][]){
if(m==0 || n==0){
return0;
}
if(dp[m][n]!=-1){
returndp[m][n];
}
if(s1.charAt(m-1)==s2.charAt(n-1)){
returndp[m][n]=1+lcss(m-1,n-1,s1,s2,dp);
}else{
returndp[m][n]=Math.max(lcss(m-1,n,s1,s2,dp),lcss(m,n-1,s1,s2,dp));
}
}
//Function to find the length of longest common subsequence in two strings.
intlcs(intx, inty, Strings1, Strings2)
{
// your code here
intdp[][]=newint [x+1][y+1];
for(inti=1;i<=x;i++){
for(intj=1;j<=y;j++){
dp[i][j]=-1;
}
}
returnlcss(x ,y ,s1,s2 ,dp );
}
System.out.println(lcs(p, q, s1, s2));
}
sc.close();
}
}