给定任意俩组字符串S1和S2,请编程输出他们间的最大相同子串。


给定任意俩组字符串S1和S2,请编程输出他们间的最大相同子串。例如:S1=12abc78,S2=7bc2,则输出为:bc


#include<iostream>
#include<string.h>
#define N 50
using namespace std;

//辅助空间,用来存储切割的字串
char sub1[N], sub2[N];

void sub_string(char *src, char *dest, int start, int end)
{
    int i;
    for(i=0; start<end; ++start, ++i)
        dest[i] = src[start];
    dest[i] = '\0';
}

char* max_substr(char *s1, char *s2)
{
    int len, len1=strlen(s1), len2=strlen(s2);
    len = len1<len2?len1:len2; //比较出两个字符串相对小的长度
    int i,j;
    //长度从大减小,从而达到比较出最大相同字串的目的
    while(len)
    {
        for(i=0; i<len1-len+1; ++i)
        {
            //截取s1串0到len长度的字串,循环往后移动
            sub_string(s1, sub1, i, i+len);
            for(j=0; j<len2-len+1; ++j)
            {
                //截取s2串0到len长度的字串,循环往后移动
                sub_string(s2, sub2, j, j+len);
                //strcmp()函数比较两个字符串如果相同,返回0;
                if(!strcmp(sub1, sub2))
                    return sub1;
            }
        }
        len--;
    }

}

int main()
{
    char s1[N], s2[N];
    cout<<"请输入s1: ";
    cin>>s1;
    cout<<"请输入s2: ";
    cin>>s2;
    cout<<max_substr(s1, s2);
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值