LCS_poj1458 Common Subsequence_空间复杂度O(n)

本文提供了一个求解最长公共子序列(LCS)问题的C++实现代码,通过动态规划方法,有效地找出两个字符串之间的最长公共子序列。适用于算法学习与编程实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求最长公共子序列,题意就不再解释了,裸地、、、、、、、、、、

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <string>

using namespace std;

int s[250], t[250];
int LCS(string s1, string s2){
    int len1 = s1.length();
    int len2 = s2.length();
    for(int i = 0; i <= len2; i++) t[i] = 0;
    for(int i = 0; i < len1; i++){
        for(int j = 0; j < len2; j++){
            if(s1[i] == s2[j]) s[j+1] = t[j] + 1;
            else s[j + 1] = s[j] > t[j + 1] ? s[j] : t[j + 1];
        }
        for(int j = 1; j <= len2; j++) t[j] = s[j];
    }
    return t[len2];
}
int main(){
    #ifdef LOCAL
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    #endif
	string s1, s2;
	while(cin>>s1>>s2){
        int n = LCS(s1,s2);
        cout<<n<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值