Skip to content

Commit

Permalink
Merge pull request #7465 from SAY-droid427/superseq-java
Browse files Browse the repository at this point in the history
Added code for shortest supersequence in Java
  • Loading branch information
siddharth25pandey committed May 31, 2021
2 parents cd144c8 + 36ed457 commit 987a49c
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions Java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ _add list here_
- [Unique BST](dp/Unique_BST.java)
- [Job Sequencing to Maximize Profit](dp/JobSequencingToMaximizeProfit.java)
- [Matrix Chain Multiplication to find the minimum cost](dp/MatrixChainMultiplication.java)
- [Shortest common supersequence](dp/shortestSupersequence.java)
- [Perfect Sum Problem](dp/PerfectSumProblem.java)
- [Floyd Warshall Algorithm](dp/FloydWarshallAlgorithm.java)
- [Subset Sum to Target](dp/SubsetSumToTarget.java)
Expand Down
68 changes: 68 additions & 0 deletions Java/dp/shortestSupersequence.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
Given two strings find out the length of the shortest supersequence formed from the two strings.
ALGORITHM:
*The idea is to find out the longest common subsequence first.
*This subsequence will be present once in both the strings.
*So on adding the length of the two strings the subsequence will be counted twice.
*Subtract the length of lcs from both the strings and add once.
*This gives length of shortest supersequence
*/

import java.util.Scanner;
import java.lang.Math;

public class shortestSuperSeq
{
public static int shortestSuperSequence(String x,String y, int n,int m)
{
int dp[][]=new int[n+1][m+1];

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(x.charAt(i-1)==y.charAt(j-1))
dp[i][j]=1+dp[i-1][j-1];
else
dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);
}
}
return dp[n][m];
}

public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter two strings: ");
String x=s.next();
String y=s.next();
int n=x.length();
int m=y.length();
System.out.println("The length of the shortest supersequence: "+(n+m-shortestSuperSequence(x,y,n,m)));
}
}

/*
Time Complexity: O(n*m)
Space complexity: O(n*m)
Input:
Enter two strings:
abc
acd
Output:
The length of the supersequence: 4
*/

0 comments on commit 987a49c

Please sign in to comment.