最長公共超級序列


最長公共超級序列是一個序列,其中包含給定序列的每個元素。換句話說,我們可以說這兩個給定的字串都是最長公共超級序列的子序列。

當兩個字串中不存在公共字元時,我們可以簡單地將它們連線起來以獲得超序列。但是當它們有一些公共字元時,首先我們必須找到最長的字串,然後新增另一個字串中的額外的字元。

輸入和輸出

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

更新於: 17-06-2020

192 檢視

開啟你的 職業生涯

完成課程以獲得認證

開始吧
廣告
© . All rights reserved.