poj 1458 Common Subsequence

本文深入探讨了如何通过LCS算法解决字符串匹配问题,并在实际应用中进行实例演示。从理论出发,逐步引导读者掌握LCS算法的核心思想和实现细节,最终通过具体案例展示其在实际场景中的应用。

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

//第一道LCS,最开始我以为是简单的遍历字符串就可以,但是提交上去WA了,再看讨论,才知道用LCS的,
//然后就上网找关于LCS的资料,在似懂非懂的情况之下敲了出来!还需要这方面的练习! 
#include <iostream>
#include <string>
#include <memory.h>
using namespace std;

const int MAXLEN = 1000;
int ans[MAXLEN][MAXLEN];

void LCSLength(string str1, string str2, int ans[][MAXLEN])
{
     int i, j, len1, len2;
     len1 = str1.length();
     len2 = str2.length();
     for (i = 1; i <= len1; i++){
         for (j = 1; j <= len2; j++){
             if (str1[i-1] == str2[j-1]){
                 ans[i][j] = ans[i-1][j-1] + 1;
             }
             else if (ans[i-1][j] >= ans[i][j-1]){
                  ans[i][j] = ans[i-1][j];
             }
             else 
                  ans[i][j] = ans[i][j-1];
         }
     }
     cout << ans[len1][len2] << endl;
}

int main()
{
    string str1, str2;
    while (cin >> str1 >> str2){
          memset(ans, 0, sizeof(ans));
          LCSLength(str1, str2, ans);
    }
    
    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值