The longest common subsequence (LCS) of dynamic programming

Longest Common Subsequence (LCS)

Problem Description

Given two strings (or sequence of numbers) A and B, find a string so that this string is the longest common part of A and B (subsequences can be discontinuous)

Sample input

sadstory

adminsorry

Sample output

6

Definition dp[i][j] represents the length of the longest common subsequence before the position i of the string s1 and the position j of the string s2.
State transition equation:

当s1[i] == s2[j]时,dp[i][j] = dp[i-1][j-1] + 1

当s1[i] != s2[j]时,dp[i][j] = max(dp[i-1][j], dp[i][j-1])

#include <bits/stdc++.h>
using namespace std;
int main(){
	string s1, s2;
	getline(cin, s1);
	getline(cin, s2);
	int len1 = s1.length();
	int len2 = s2.length();
	int dp[len1+1][len2+1];				//因为状态转移方程-1,因此得从1开始 
	for(int i = 0; i <= len1; i++){		//并设定初始化 
		for(int j = 0; j <= len2; j++){
			dp[i][j] = 0;
		}
	}
	for(int i = 1; i <= len1; i++){
		for(int j = 1; j <= len2; j++){
			if(s1[i-1] == s2[j-1]){
				dp[i][j] = dp[i-1][j-1] + 1;
			}else{
				dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
			}
		}
	}
	cout<<dp[len1][len2];
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44723496/article/details/109058377