最长公共子串 Longest-Common-Substring(LCS)

    给定两个字符串X,Y,求二者最长的公共连续子串,如 X = [abcdefg],Y = [bacdegf],二者的最长公共连续子串是 cde 长度为3,

这里讨论 DP 方案。

    考虑 m = X.length,n = Y.length 开辟一个大小为 m x n 的数组 d[m][n],使用 d[i][j] 表示以 X[i] 与 Y[j] 结尾的最长公共子串的长度,因为要求子串连续,所以对于 X[i] 与 Y[j],它们要么与之前的公共子串构成新的公共子串,要么就是不构成公共子串,故状态转移方程为

  • 1.If X[i] == Y[j], then dp[i][j] = dp[i-1][j-1] + 1
  • 2. If X[i] != Y[j], then dp[i][j] = 0


#include <iostream>
#include <vector>
#include <string>

using namespace std;

#define INF (~(1<<31))

int main(){
	string s1, s2;
	cin >> s1 >> s2;

	vector<vector<int>> mat(s1.size(), vector<int>(s2.size(), 0));
	int pos = 0, maxLen = -INF;

	for(size_t i = 0; i < s1.size(); ++i){
		for(size_t j = 0; j < s2.size(); ++j){
			if(s1[i] == s2[j]){
				if(i == 0 || j == 0){
					mat[i][j] = 1;
				}else{
					mat[i][j] = mat[i-1][j-1] + 1;
				}
			}

			if(maxLen < mat[i][j]){
				maxLen = mat[i][j];
				pos = i+1-maxLen;
			}
		}
	}

	cout << s1.substr(pos, maxLen);

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值