Compute the shortest string for a combination of two given strings such that the new string consist of both the strings as its subsequences.
Input : a = "pear" b = "peach" Output : pearch pearch is the shorted string such that both pear and peach are its subsequences. Input : a = "geek" b = "code" Output : gecodek
We have discussed a solution to find length of the shortest supersequence in below post.
Shortest Common Supersequence
In this post, printing of supersequence is discussed. The solution is based on below recursive approach discussed in above post as an alternate method.
Let a[0..m-1] and b[0..n-1] be two strings and m and be respective lengths. if (m == 0) return n; if (n == 0) return m; // If last characters are same, then add 1 to // result and recur for a if (a[m-1] == b[n-1]) return 1 + SCS(a, b, m-1, n-1); // Else find shortest of following two // a) Remove last character from X and recur // b) Remove last character from Y and recur else return 1 + min( SCS(a, b, m-1, n), SCS(a, b, m, n-1) );
We build a DP array to store lengths. After building the DP array, we traverse from bottom right most position. The approach of printing is similar to printing LCS.
Solution based on LCS:
We build the 2D array using LCS solution. If the character at the two pointer positions is equal, we increment the length by 1, else we store the minimum of the adjacent positions. Finally, we backtrack the matrix to find the index vector traversing which would yield the shortest possible combination.
This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count number of strings (made of R, G and B) using given combination
- Sum of products of all combination taken (1 to n) at a time
- Find the resulting Colour Combination
- Python | Print all string combination from given numbers
- Search in an array of strings where non-empty strings are sorted
- Meta Strings (Check if two strings can become same after a swap in one string)
- Number of common base strings for two strings
- Count of strings that become equal to one of the two strings after one removal
- Pairs of complete strings in two sets of strings
- Shortest Uncommon Subsequence
- Shortest Common Supersequence
- Shortest Superstring Problem
- Multistage Graph (Shortest Path)
- Printing Shortest Common Supersequence
- Shortest substring of a string containing all given words
Improved By : Ita_c