找两个字符串中的最长公共子串

HHU数据结构第一次实验Homework
该题目主要涉及字符串操作和动态规划
效果如图:
在这里插入图片描述
具体代码实现如下:

#include <algorithm>
#include <iostream>

using namespace std;

string longestCommonStr(string test1, string test2) {
   int n = test1.size(), m = test2.size();

   int len = 0, res = 0;
   int row = 0, col = m - 1; // 从右上角开始

   int lcs_i = 0, lcs_j = 0;

   // 计算矩阵中的每一条斜线上的值
   while (row < n) {
       int i = row, j = col; // 斜线起点
       while (i < n && j < m) { // 遍历当前斜线
           if (test1[i] == test2[j]) {
               len++;
               if (len > res) {
                   res = len;
                   lcs_i = i, lcs_j = j; // 记录最大长度子串的最后一个元素(i,j)
               }
           }
           else len = 0; // 断开后,len重新算
           i++, j++;
       }
       len = 0; // 下一条斜线 len 从 0 开始

       // 改变斜线起点
       if (col > 0) col--;
       else row++;
   }

   string Result;
   row = lcs_i, col = lcs_j;
   while (row >= 0 && col >= 0) {
       if (test1[row] == test2[col]) Result += test1[row];
       else break;
       row--, col--;
   }

   reverse(Result.begin(), Result.end());

   if (res == 0)
   {
       cout << "不存在该子串:" << endl;
       return "-1";
   }

   else
   {
       cout << "最长子串为:" << endl;
       return Result;
   }
}

int main() {
   string a, b;
   cout << "分别开始对子串1和子串2赋值:\n" << endl;
   cin >> a >> b;
   cout << '\n';
   cout << longestCommonStr(a, b);
   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早安不安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值