题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <stdio.h> #include <string.h> int main() { char sht[310] = {0}; char lon[310] = {0}; gets(sht); gets(lon); if(strlen(sht) > strlen(lon)) { char tmp[310] = {0}; strcpy(tmp, lon); strcpy(lon, sht); strcpy(sht, tmp); } int sht_len = strlen(sht); int lon_len = strlen(lon); char *find = NULL; int maxlen = 0; int tmp = 0; int begin = 0; for(int i = 0; i < sht_len; ++ i) { //以sht[i]为首的子串 for(int j = 0; j < lon_len; ++ j) { if(sht[i] == lon[j]) { tmp = 1; for(int k = 1; sht[i+k] == lon[j+k]; ++ k) { ++ tmp; } if(tmp > maxlen) { maxlen = tmp; begin = i; } } } } for(int i = 0; i < maxlen; ++ i) { putchar(sht[begin+i]); } return 0; }