最長公共子序列

1.最長公共子序列(Longest Common Subsequence,LCS)

案例:求str1,str2最長公共子串長度

狀態描述:dp[i][j] 表示str1前i個字符串與str2前j個字符串最長公共子串長度

狀態分析:(1)當str1[i]=str2[j]時,在取str1的前i-1和str2的前j-1公共子串最長+1

                  (2) 當str1[i]!=str2[j]時,取最長,則判斷str1的前i-1和str2的前j公共子串長度與str1的i和str2的j-1公共子串長度

狀態轉換方程如下遞歸方程

\\ F[0][j] & =0;\\ F[i][0] & =0;\\ F[i][j] & = \begin{cases} F[i-1][j-1]+1, & \text {S1[i]=S2[j]} \\ max\lbrace F[i-1][j],F[i][j-1] \rbrace, & \text{S1[i]!=S2[j]} \end{cases}

結果存儲dp[str1.len][str2.len]中

Code:

/**
 * Longest Common Subsequence
 */
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
vector<int> dpcol(100,0);
vector<vector<int>> dp(100,dpcol);
int main(){
	string str1,str2;
	while(cin>>str1>>str2){
		int n=str1.length();
		int m=str2.length();
		for(int i=0;i<=n;i++) {
			dp[0][i]=0;
			dp[i][0]=0;
		}
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				if(str1[i-1]==str2[j-1]){
					dp[i][j]=dp[i-1][j-1]+1;
				}
				else{
					dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
				}
			}
		}//時間複雜度L1*L2,空間複雜度L1*L2
		cout<<dp[n][m]<<endl;
	}
	return 0;
}
/**
abcd
cxbydz
2
 */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章