HJ65 查找两个字符串a,b中的最长公共子串

描述

查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。

注:子串的定义:将一个字符串删去前缀和后缀(也可以不删)形成的字符串。请和“子序列”的概念分开!

数据范围:字符串长度1\le length \le300 \1≤length≤300 

进阶:时间复杂度:O(n^3)\O(n3) ,空间复杂度:O(n)\O(n) 

输入描述:

输入两个字符串

输出描述:

返回重复出现的字符

示例1

输入:

abcdefghijklmnop
abcsafjklmnopqrstuvw

复制输出:

jklmnop

#include <algorithm>
#include <iostream>
#include <map>
#include <string.h>

//检查最长子串是否在另一个中出现,如果出现返回true,否则返回false
bool checkAppear(std::string subStr, std::string parStr)
{
    const char* rtn = strstr(parStr.c_str(), subStr.c_str());
    if(rtn != nullptr)
    {
        return true;
    }

    return false;
}
/*
abcdefghijklmnop
abcsafjklmnopqrstuvw
*/
std::string maxLengthPublicSubstr(std::string str1, std::string str2)
{
    std::string minStr = "";
    std::string maxStr = "";
    int minlen = std::min(str1.length(), str2.length());
    if(minlen == str1.length())
    {
        minStr = str1;
        maxStr = str2;
    }
    else
    {
        minStr = str2;
        maxStr = str1;
    }

    std::string rtnStr = "";
    //从长到短截取字串
    for(int i = 0; i < minlen; ++i)
    {
        for(int j = minlen-1; j > i; --j)
        {
            std::string temp = minStr.substr(i, j - i + 1);         
            // std::cout << "temp = " << temp << std::endl;
            bool flag = checkAppear(temp, maxStr);
            if(flag)
            {
                if(temp.length() > rtnStr.length())
                {
                    rtnStr = temp;
                }
            }
        }
    }
    return rtnStr;
}

int main()
{
    std::string str1;
    std::string str2;
    getline(std::cin, str1);
    getline(std::cin, str2);
    std::cout << maxLengthPublicSubstr(str1, str2) << std::endl;

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值