0
点赞
收藏
分享

微信扫一扫

leetcode-1143. 最长公共子序列

Python芸芸 2022-04-13 阅读 70
c++leetcode

leetcode-1143. 最长公共子序列

题目

在这里插入图片描述

代码

动态规划

#include <iostream>
#include <vector>
using namespace std;

int longestCommonSubsequence(string text1, string text2) {
	int m = text1.size();
	int n = text2.size();
	if(m == 0 || n == 0){
		return 0;
	}
	vector<vector<int> > dp(m+1, vector<int>(n+1, 0));
	for(int i = 1; i <= m; i++){
		for(int j = 1; j <= n; j++){
			if(text1[i-1] == text2[j-1]){
				dp[i][j] = dp[i-1][j-1] + 1;
			}else{
				dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
			}
		}
	}
	return dp[m][n];
}

int main(){
	string text1, text2;
	cin>>text1>>text2;
	int res;
	res = longestCommonSubsequence(text1, text2);
	cout<<res;
	return 0;
}
举报

相关推荐

0 条评论