我覺得吧最好是會一種方法然後背下來,這樣就不會像博主一樣在打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();
}