题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
//题目要求保证输出在较短串中最先出现的那个,则保证str1为最短,并以str1为准,先遍历str2,再遍历str1,判断子串并计算长度,计算一次长度判断一次最长子串值,并存储至数组,用于最后输出 #include <stdio.h> #include <string.h> int main() { char str1[301], str2[301], ans[301]; int i, j, n, max; while(scanf("%s %s",str1,str2) != EOF) { if(strlen(str1) > strlen(str2)) //保持str1为最短的 { char temp[1000]; strcpy(temp,str1); strcpy(str1,str2); strcpy(str2,temp); } max = 0; for(i=0; i<strlen(str1);i++) //以str1为准,遍历str2,再遍历str1,保证输出在较短串中最先出现的那个 { for(j=0; j<strlen(str2);j++) { n = 0; while(str1[i+n] == str2[j+n] && str1[i+n] != '\0') //判断str2与str1相等的子串,并计算子串长度 { n++; } if(n>max) //子串长度大于前一寄存的子串长度,则替换,并将子串复制至数组ans(注意截取字符串方式为给最后一位置'\0'),用于输出子串。 { max = n; strcpy(ans, str1+i); ans[max] = '\0'; } } } printf("%s\n",ans); } return 0; }