最长公共子串

最长公共子串

题目描述

给定两个字符串str1和str2,输出两个字符串的最长公共子串,如果最长公共子串为空,输出-1。

输入描述:

输入包括两行,第一行代表字符串srr1,第二行代表字符串str2。 ( 1 ≤ l e n g t h ( s t r 1 ) , l e n g t h ( s t r 2 ) ≤ 5000 ) \left( 1\leq length(str1),length(str2) \leq 5000 \right) (1length(str1),length(str2)5000)

输出描述:

输出包括一行,代表最长公共子串。

示例1
输入
1AB2345CD
12345EF
输出
2345
备注:

时间复杂度 O ( n 2 ) O(n^{2}) O(n2) ,额外空间复杂度 O ( 1 ) O(1) O(1)。(n可以为其中任意一个字符串长度)


题解:

状态转移方程为:
F [ i , j ] = { F [ i − 1 , j − 1 ] + 1 s t r 1 [ i ] = s t r 2 [ j ] 0 s t r 1 [ i ] ≠ s t r 2 [ j ] F[i, j] = \left\{ \begin{aligned} F[i-1, j-1] + 1 && str1[i] = str2[j] \\ 0 && str1[i] \neq str2[j] \end{aligned} \right. F[i,j]={F[i1,j1]+10str1[i]=str2[j]str1[i]=str2[j]
普通解法: 使用额外的二维状态数组进行状态表示(这种写法很简单,在输出时,需要记录最大值以及最大长度的终点)

普通解法代码:
#include <cstdio>
#include <cstring>

using namespace std;

const int N = 5010;

int f[N][N];
char str1[N];
char str2[N];

int main(void) {
    scanf("%s", str1);
    scanf("%s", str2);
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    int max_len = 0, idx = 0;
    for (int i = 1; i <= len1; ++i) {
        for (int j = 1; j <= len2; ++j) {
            if (str1[i - 1] == str2[j - 1]) f[i][j] = f[i - 1][j - 1] + 1;
            if (f[i][j] > max_len) {
                max_len = f[i][j];
                idx = i;
            }
        }
    }
    if (idx == 0) return 0 * puts("-1");
    for (int i = idx - max_len; i < idx; ++i) putchar(str1[i]);
    return 0 * puts("");
}
进阶解法:

题目要求额外的空间复杂度为 O ( 1 ) O(1) O(1) ,上面的解法肯定不行,但是我们观察上面的状态转移方程,发现每个状态只跟左上角的状态有关,我们可以按照斜线方向计算所有的值,于是我们可以只用一个变量就可以计算出所有位置的值。

进阶解法代码:
#include <cstdio>
#include <cstring>

using namespace std;

const int N = 5010;

char str1[N];
char str2[N];

int main(void) {
    scanf("%s", str1);
    scanf("%s", str2);
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    int row = 0, col = len2 - 1;
    int max_len = 0, ends = 0;
    while (row < len1) {
        int i = row, j = col;
        int ans = 0;
        while (i < len1 && j < len2) {
            if (str1[i] != str2[j]) ans = 0;
            else ans += 1;
            if (ans > max_len) {
                max_len = ans;
                ends = i;
            }
            ++i, ++j;
        }
        if (col) --col;
        else ++row;
    }
    if (!ends) return 0 * puts("-1");
    for (int i = ends - max_len + 1; i <= ends; ++i) putchar(str1[i]);
    return 0 * puts("");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值