给定两个输入文本,找出它们共有的最长字符串
- //求两字符串的最长公共子串
- #include<stdio.h>
- #include<string.h>
- char * maxsamesubstring(char *s1,char *s2)
- {
- int i,j,len,maxlen,index,maxindex;
- maxlen=0; //初始化最长公共子串的长度
- maxindex=0; //初始化最长公共子串的位置
- len=0; //当前公共子串的长度
- for(i=0;s1[i]!='\0';i++)
- for(j=0;s2[j]!='\0';j++)
- if(s1[i+len]==s2[j])
- {
- if(!len)//len=0 的时候执行(第一次执行)
- {
- index=j; //记下公共子串的起始位置
- }
- len++;
- }
- else if(len)
- {
- if(maxlen<len) //经过一次扫描找到了最长公共子串
- {
- maxlen=len;
- maxindex=index;
- }
- len=0; //进行下一次的扫描
- }
- char *p=new char[maxlen+1];
- strncpy(p,s2+maxindex,maxlen); //把最长公共字符串复制到p所指的空间
- p[maxlen+1]='\0'; //置串结束标志
- return p;
- }
- int main()
- {
- char *s1="hello world",*s2="fuck world",*sub;
- sub=maxsamesubstring(s1,s2);
- printf("%s\n",sub);
- return 0;
- }