Skip to content

Commit

Permalink
Merge pull request #48 from farhan-sayeed/feat/lcs
Browse files Browse the repository at this point in the history
Implemented Longest Common Subsequence in Java
  • Loading branch information
sudo-parnab authored Oct 30, 2024
2 parents 34f7095 + 7a18998 commit 59e59a0
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Dynamic Programming/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Recursive implementation of LCS problem in java
import java.io.*;
import java.util.*;

class Main {

// Returns length of LCS for S1[0..m-1], S2[0..n-1]
static int lcs(String S1, String S2, int m, int n) {
if (m == 0 || n == 0)
return 0;
if (S1.charAt(m - 1) == S2.charAt(n - 1))
return 1 + lcs(S1, S2, m - 1, n - 1);
else
return Math.max(lcs(S1, S2, m, n - 1),
lcs(S1, S2, m - 1, n));
}

public static void main(String[] args) {
String S1 = "AGGTAB";
String S2 = "GXTXAYB";
int m = S1.length();
int n = S2.length();

System.out.println("Length of LCS is"
+ " " + lcs(S1, S2, m, n));
}
}
28 changes: 28 additions & 0 deletions Dynamic Programming/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
## Longest Common Subsequence (LCS)

Given two strings, S1 and S2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters and without changing the relative order of the remaining characters. For example , subsequences of “ABC” are “”, “A”, “B”, “C”, “AB”, “AC”, “BC” and “ABC”. In general a string of length n has 2n subsequences.

LCS problem has great applications like diff utility (find the difference between two files) that we use in our day to day software development.

**Examples:**

```
Input: S1 = “ABC”, S2 = “ACD”
Output: 2
Explanation: The longest subsequence which is present in both strings is “AC”.
```

Approach Used: Using Recursion – O(2^min(m,n)) Time and O(min(m, n)) Space

```
The idea is to compare the last two characters. While comparing the strings S1 and S2 two cases arise:
1. Match : Make the recursion call for the remaining strings (strings of lengths m-1 and n-1) and add 1 to result.
2. Do not Match : Make two recursive calls. First for lengths m-1 and n, and second for m and n-1. Take the maximum of two results.
Base case : If any of the strings become empty, we return 0.
```

0 comments on commit 59e59a0

Please sign in to comment.