最長公用子序列

來源:互聯網
上載者:User

標籤:

最長公用子序列:

求兩個序列中最長的公用子序列演算法,要區別於最長公用字串(其要求連續)。

如:字串acdfg與adfc的最長公用子序列為adf。

假設c(i,j)記錄序列Xi和Yj的最長公用子序列的長度,滿足下列公式:

程式實現:

 1 /*************************************** 2 FileName LongestCommonSubsequence.cpp 3 Author : godfrey 4 CreatedTime : 2016/5/1 5 ****************************************/ 6 #include <iostream> 7 #include <cstring> 8 #include <vector> 9 #include <algorithm>10 #include <stdio.h>11 #include <stdlib.h>12 13 using namespace std;14 15 void LongestCommonSubsequence(const char* str1,const char* str2,string& str){16     int size1 = (int)strlen(str1);17     int size2 = (int)strlen(str2);18     const char* s1 = str1-1;19     const char* s2 = str2-1;20     vector<vector<int> >chess(size1+1,vector<int>(size2+1));21     int i,j;22     //設定棋局23     for(i=0;i<=size1;i++)24         chess[i][0] = 0;25     for(j=0;j<=size2;j++)26         chess[0][j] = 0;27     for(i=1;i<=size1;i++){28         for(j=1;j<=size2;j++){29             if(s1[i]==s2[j])30                 chess[i][j] = chess[i-1][j-1] + 1;31             else32                 chess[i][j] = max(chess[i][j-1],chess[i-1][j]);33         }34     }35 36     i = size1;37     j = size2;38     //逆推儲存39     while((i!=0) && (j!=0)){40         if(s1[i]==s2[j]){41             str.push_back(s1[i]);42             i--;43             j--;44         }45         else{46             if(chess[i][j-1]>chess[i-1][j])47                 j--;48             else49                 i--;50         }51     }52     reverse(str.begin(),str.end());53 }54 55 int main()56 {57     const char* str1 = "TCGGATCGACTT";58     const char* str2 = "AGCCTACGTA";59     string str;60     LongestCommonSubsequence(str1,str2,str);61     cout<<str.c_str()<<endl;62     return 0;63 }

運行結果:

說明:事實上,兩個字串可能存在多個子序列長度相同並且最大,因此,最長公用子序列是個序列集合。

轉載請註明出處:

C++部落格園:godfrey_88

http://www.cnblogs.com/gaobaoru-articles/

 

最長公用子序列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.