我觉得吧最好是会一种方法然后背下来,这样就不会像博主一样在打oj比赛的时候现想......浪费了两个小时的时间(www)
- main idea
字符串一不动;
修改字符串二尾的\0使其不断前移,每向前移动一个字符,都使指向字符串二的头的指针依次后移,用strstr找其中是否有与字符串一相同的字符串,若有就比较并赋值max;
- code demo(IDE VS2017)
//求两个字符串的最长公共子串
#include<stdio.h>
#include<string.h>
int lcs(char *p1, char *p2) //传入两个指向字符数组的指针,返回最长公共字串的长度
{
int max = 0, i, len2 = strlen(p2);
char *p3;
for (i = len2;i > 0;i--)
{
p2[i] = '\0';//其实第一个\0越界了,赋值完是原来的字符串不变,最后一个\0赋完刚好就剩第一个字符
p3 = p2;
while (*p3)//p3后移直到其中没有字符
{
if (strstr(p1, p3))//如果有相同的字符串
{
max = max > strlen(p3) ? max : strlen(p3);
break;//这个肯定是一重循环里最大的解,跳出即可
}
p3++;
}
}
return max;
}
int main() {
char a[100];
char b[100];
gets(a);
gets(b);
printf("%d", lcs(a, b));
getchar();
}