题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
//有顺序需要两个for遍历,以最短的一个字符串为基准,设置变量n作为判断相同的移动标尺,每次与最长字符串做完比较,需与子串当前长度最大值比较保证当前最大值有效。 #include <stdio.h> #include <string.h> int main() { char str1[151] = {0}, str2[151] = {0}, temp[151] = {0}; int i = 0, j = 0, n = 0, max = 0; while(scanf("%s %s", str1, str2) != EOF) { if( strlen(str1) > strlen(str2) ) { strcpy(temp, str1); strcpy(str1,str2); strcpy(str2, temp); } } 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("%d\n", max); return 0; }