cy568searchx

 网上存在一些找出两个字符串中最大的公共子串的代码,但是在我看来他们写的都太复杂了,所以我也写了一个算法,效率不算高,还凑合,但是我觉的他的实现比较简单,代码也比较好维护,代码如下:

 

  #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;

}

 

如果谁有更简单的实现方法,期待分享。

分类:

技术点:

相关文章:

  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
猜你喜欢
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
相关资源
相似解决方案