- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Shortest Common Super Sequence
Shortest common super-sequence is a sequence where each element of both of the given sequences is present. In other words, we can say that the given two strings, both are sub-sequence of Shortest Common Super-Sequence.
When there are no common characters in two strings, then we can simply concatenate them to get Super-sequence. But when they have some common characters, then firstly we have to find the longest string, then add extra characters of the other string.
Input and Output
Input: Two strings. “ABCDEF” and “XYDEF” Output: The length of the shortest common super-sequence. Here the super-sequence is “ABCDEFXY”. So the length is 8.
Algorithm
superSeq(str1, str2)
Input: Two strings str1 and str2.
Output: Find length of super sequence.
Begin m := length of str1 n := length of str2 define table named seqTab of size (m+1 x n+1) for i := 0 to m, do for j := 0 to n, do if i = 0, then seqTab[i, j] := j else if j = 0, then seqTab[i, j] := i else if str1[i-1] = str2[j-1], then seqTab[i, j] := 1 + seqTab[i-1, j-1] else seqTab[i, j] := 1 + minimum of seqTab[i-1, j] and seqTab[i, j-1] done done return seqTab[m, n] End
Example
#include<iostream> using namespace std; int min(int a, int b) { return (a<b)?a:b; } int superSeq(string str1, string str2) { int m = str1.size(); int n = str2.size(); int supSeqTable[m+1][n+1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (!i) supSeqTable[i][j] = j; //shortest supersequence length is j else if (!j) supSeqTable[i][j] = i; //shortest supersequence length is i else if (str1[i-1] == str2[j-1]) supSeqTable[i][j] = 1 + supSeqTable[i-1][j-1]; else supSeqTable[i][j] = 1 + min(supSeqTable[i-1][j], supSeqTable[i][j-1]); } } return supSeqTable[m][n]; } int main() { string first = "ABCDEF"; string second = "XYDEF"; cout << "Length of the shortest supersequence is " << superSeq(first, second); }
Output
Length of the shortest supersequence is 8
Advertisements