当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
C语言实例编程:C语言实现寻找最大公共子字符串
发布时间:2010/1/25 21:16:29 来源:城市学习网 编辑:海蓝

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

  // 此题用for能控制循环,思路比下面的while更容易看懂

  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;

  }

  }

  }

  } [NextPage]

  char *maxsubstr(char *str1, char *str2)

  {

  char *p1, *p2, *q1, *q2, *destp;

  char *substr;

  int max = 0, len;

  p1 = str1;

  while (*p1 != '')

  {

  q1 = str2; //每次是从str2的头部开始的

  while (*q1 != '')

  {

  len = 0;

  p2 = p1; q2 = q1;

  while ((*p2 != '') && (*q2 != ''))

  {

  if (*p2 == *q2)  //如果有个相同的,则继续查找

  {

  p2++; q2++; len++;

  }

  else

  break;

  }

  if (len > max)

  {

  max = len; destp = p1;

  }

  q1++; // 继续查找str2中的下一个

  }

  p1++; // 以str1中的下一个关键字进行查找

  }

  substr = (char *)malloc(sizeof(char)*max);

  strncpy(substr,destp,max);

  return substr;

  }

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved