• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
乐碎碎
程序媛想的事儿
博客园    首页    新随笔    联系   管理    订阅  订阅
最大公共子串
 1 #include "stdafx.h"
 2 #include <string.h>
 3 #include <stdio.h>
 4 #define MAX 100
 5 
 6 //在字符串str1和str2中查找最大的公共子串maxsubstr
 7 void findmaxsubstr(const char *str1,const char *str2,char *maxsubstr)
 8 {
 9     int maxlen=0,maxpos=-1;
10     int k;
11     for(int i=0;i<strlen(str1);i++)
12     {
13         for(int j=0;j<strlen(str2);j++)
14         {
15             if(str1[i]==str2[j])
16             {
17                 k=1;
18                 while((str1[i+k]==str2[j+k])&&(str1[i+k]!='\0'))
19                 {
20                     k++;
21                     if(k>maxlen)
22                     {
23                         maxlen=k; //maxlen最大的子串长度
24                         maxpos=i; //maxpos最大的子串在str1中的位置
25                     }
26                 }
27             }
28         }
29     }
30     if (maxpos==-1)
31         maxsubstr[0]='\0';
32     else
33     {
34         memcpy(maxsubstr,str1+maxpos,maxlen);
35         maxsubstr[maxlen]='\0';
36     }
37 }
38 
39 void main()
40 {
41     char maxsubstr[MAX];
42     findmaxsubstr("abcdefg","xbcyefg",maxsubstr);
43     printf("%s\n",maxsubstr);
44 }

 

 

 

posted on 2012-10-04 18:16  xingle0917  阅读(242)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3