华为OJ 75 公共子串计算 动态规划 最长公共子串

1. 题目描述

1.1. Limit

Time Limit: 1000 ms

Memory Limit: 131072 kB

1.2. Problem Description

计算两个字符串的最大公共字串的长度,字符不区分大小写


1.3. Input

输入两个字符串


1.4. Output

输出一个整数


1.5. Sample Input

asdfas
werasdfaswer

1.6. Sample Output

6

1.8. Source

华为OJ 75 公共子串计算


2. 解读

动态规划。 list[i][j]表示以str1[i]和str2[j]结尾的最长公共子串, 递推方程如下。

l i s t [ i ] [ j ] = { l i s t [ 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 ] ) list[i][j] ={\left\{ \begin{aligned} & list[i - 1][j - 1] + 1 & , (str1[i] = str2[j]) \\ & 0 & , (str1[i] \neq str2[j]) \\ \end{aligned}\right. } list[i][j]={list[i1][j1]+10,(str1[i]=str2[j]),(str1[i]=str2[j])

3. 代码

#include<iostream>
using namespace std;

const int MAXM = 1e3 + 1;

int main(){
    string str1, str2;
    cin>>str1>>str2;
    int list[MAXM][MAXM] = {{0}};
    int maxAns = 0;
    for(int i = 1; i <= str1.size(); i++){
        for(int j = 1; j <= str2.size(); j++){
            if(toupper(str1[i-1])==toupper(str2[j-1])){
                // list[i][j]表示以str1[i]和str2[j]结尾的最长公共子串
                list[i][j] = list[i - 1][j - 1] + 1;
                maxAns = max(maxAns, list[i][j]);
            }else{
                list[i][j] = 0;
            }
        }
    }
    cout<<maxAns<<endl;
}

联系邮箱:curren_wong@163.com

CSDN:https://me.csdn.net/qq_41729780

知乎:https://zhuanlan.zhihu.com/c_1225417532351741952

公众号:复杂网络与机器学习

欢迎关注/转载,有问题欢迎通过邮箱交流。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值