找出两个字符串中最大公共子字符串,如"abccade"、"dgcadde"的最大子串为"cad"

来源:互联网 发布:qq头像ps源码 编辑:程序博客网 时间:2024/06/05 14:08
//// 此题用for能控制循环
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; 
    }
  }
 }
}


下面是我的程序:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char *find_common(char *str1, char *str2)
{
     int as,bs,i = 0,j = 0;//记录字符移动位置
     int maxlen = 0,count; //记录最大公共子串的长度
     int len1 = 0,len2 = 0;//保存待测字符的长度
     char *string;//保存最大公共子串
     while(*(str1 + len1) != '\0')
     {
          len1++;
     }
     while(*(str2 + len2) != '\0')
     {
          len2++;
     }
     string = (char *)malloc(len1 > len2 ? len1 : len2);//动态分配内存
     for(i=0; i<len1; i++)
          for(j=0; j<len2; j++)
          {
               if(*(str1 + i) == *(str2 + j))
               {
                    as = i;
            bs = j;
    count = 1;
    while(as + 1 < len1 && bs + 1 < len2 && str1[++as] == str2[++bs]) //查找最大相等长度 
     count++;

    if(count > maxlen)
    {
     maxlen = count;
     strncpy(string, str1+i, maxlen);
    }   
   } 
 *(string + maxlen) = '\0'; 
}
 return string;

}

int main()
{
 char *str1 = NULL;
 char *str2 = NULL;
 char *maxstring;
 str1 =(char *)malloc(256);
 str2 =(char *)malloc(256);
 printf("Please input the first string:");
 scanf("%s",str1);
 printf("Please input the second string:");
 scanf("%s",str2);
 maxstring = find_common(str1, str2);
 printf("The maxlen is: %s\n",maxstring);
 free(maxstring);
 free(str2);
 free(str1);
 return 0;
}
0 0