公共字串计算(最长公共子串/序列)C++

这篇博客介绍了如何使用C++解决计算两个字符串的最大公共字串长度问题,包括暴力求解和动态规划的方法。博主详细阐述了动态规划的状态转移方程,并给出了矩阵填充规则。文章提供了多个参考资料链接,帮助读者深入理解最长公共子串和子序列的概念。

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

题目

描述

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

输入

输入两个字符串

输出

输出一个整数

样例输入

asdfas werasdfaswer

样例输出

6

思路

暴力求解
此题用cin即可

代码

#include <iostream>
#include <string>
using namespace std;
int Maxsubstr(string a,string b)
{
    unsigned int start1,start2;
    int count=0,Max=0;
    for(unsigned int i=0; a[i]!='\0'; i++)
    {
        for(unsigned int j=0; b[j]!='\0'; j++)
        {
            start1=i;
            start2=j;
            while(a[start1]==b[start2] && start1<a.length() && start2<b.length())
            {
                start1++;
                start2++;
                count++;
            }
            if(count>Max)
            {
                Max=count;
            }
            count=0;
        }
    }
    return Max;
}

int main()
{
    string str1,str2;
    cin>>str1;
    cin>>str2;
    //不区分大小写
    for (unsigned int i=0; i<str1.length(); i++)
    {
        str1[i]=tolower(str1[i]);
    }
    for (unsigned int i=0; i<str2.length(); i++)
    {
        str2[i]=tolower(str2[i]);
    }
    cout<<Maxsubstr(str1,str2)<<endl;
}

这里写图片描述

题目

描述

查找两个字符串a,b中的最长公共子串。
详细描述:
查找两个字符串a,b中的最长公共子串。

输入

输入两个字符串

输出

返回重复出现的字符

样例输入

abcdefghijklmnop
abcsafjklmnopqrstuvw

样例输出

jklmnop

思路

暴力求解

代码

#include <iostream>
#include <string>
using namespace std;
int Maxsubstr(string a,string b,string *&s)
{
    unsigned int start,start1,start2;
    int count=0,Max=0;
    for(unsigned int i=0; a[i]!='\0'; i++)
    {
        for(unsigned int j=0; b[j]!='\0'; j++)
        {
            start1=i;
            start2=j;
            while(a[start1]==b[start2] && start1<a.length() && start2<b.length())
            {
                start1++;
                start2++;
                count++;
            }
            if(count>Max)
            {
                start = i;
                Max = count;
            }
            count=
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值