最短公共超序列
最短的公共超序列是其中两个给定序列的每个元素都存在的序列。换句话说,我们可以说给定的两个字符串都是最短公共超序列的子序列。
当两个字符串中没有公共字符时,我们可以简单地将它们连接起来以获得超序列。但是,当它们具有一些公共字符时,首先我们必须找到最长的字符串,然后在另一个字符串中添加额外的字符。
输入输出
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.
算法
superSeq(str1, str2)
输入:两个字符串str1和str2。
输出:查找超序列的长度。
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
示例
#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);
}
输出结果
Length of the shortest supersequence is 8
以上是 最短公共超序列 的全部内容, 来源链接: utcz.com/z/316162.html