精品理论电影在线_日韩视频一区二区_一本色道精品久久一区二区三区_香蕉综合视频

C語言實現尋找最大公共子字符串

發布時間:2011-09-16 共2頁

  找出兩個字符串中最大公共子字符串,如"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;

  }

  }

  }

  }

百分百考試網 考試寶典

立即免費試用