#include<iostream>
#include<cstring>
#include<cassert>
using namespace std;
//找出两个字符串中最长的公共子串(如果存在多个 , 返回第一个)
//参数:str1 字符串1
// str2 字符串2
// maxSubStr 找到的最大子串
void findMaxSubstr(const char * str1 , const char * str2 , char * maxSubstr){
assert((str1!=NULL)&&(str2!=NULL));
assert(maxSubstr!=NULL);
int maxPos=-1;
int maxLen=0;
for(int i=0; i<strlen(str1); i++)
{
for(int j=0; j<strlen(str2); j++)
{
if(str1[i]==str2[j])
{
for(int k=1; (str1[i+k]==str2[j+k])&&(str1[i+k]!='\0'); k++);
if(k>maxLen)
{
maxPos=i;
maxLen=k;
}
}
}
}
if(maxPos==-1)
{
maxSubstr[0]='\0';
}
else
{
memcpy(maxSubstr , str1+maxPos , maxLen);
maxSubstr[maxLen]='\0';
}
}
int main()
{
char substr[20];
findMaxSubstr("zhangligu" , "gligzhangligu" , substr);
cout<<substr<<endl;
return 0;
}
找出两个字符串中最大的公共子串的简单实现
最新推荐文章于 2023-04-10 22:00:26 发布