现在的位置: 首页 > 综合 > 正文

找出两个字符串中最大公共子字符串

2013年07月16日 ⁄ 综合 ⁄ 共 1293字 ⁄ 字号 评论关闭

转帖地址:http://blog.csdn.net/laibinghua/archive/2010/09/26/5906541.aspx

http://www.cnblogs.com/kanong/archive/2010/09/01/1815337.html

 

int GetCommon(char *s1, char *s2, char **r1, char **r2)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int maxlen = 0;
for(int i = 0; i < len1; i++)
{
     for(int j = 0; j < len2; j++)
     {
          if(s1[i] == s2[j])
          {
               int as = i, bs = j, count = 1;
               while(as + 1 < len1 && bs + 1 < len2 && s1[++as] == s2[++bs])
                   count++;
               if(count > maxlen)
               {
                   maxlen = count;
                   *r1 = s1 + i;
                   *r2 = s2 + j;
               }
          }
     }
}
return maxlen;
}

void main()
{
char *r1,*r2;
char *str1="nbasdfghjkl",*str2="asdfgbhjnmk";
cout<<GetCommon(str1,str2,&r1,&r2);
for(int i=0;i<GetCommon(str1,str2,&r1,&r2);i++)
     cout<<*(r2+i);
}

 

 

======================================================================

 

 

 

void findMaxSubstr(const char *str1,const char *str2,char *maxSubstr)
{
 int maxPos=-1;
 int maxLen=0;
 for(unsigned int i=0;i<strlen(str1);i++)
 {
  for(unsigned 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';
 }
}

抱歉!评论已关闭.