题解 | #公共子串计算#
公共子串计算
http://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
//字符串匹配:
//asdfas
#define MAXROOM 1000
void getCommon(const char *str1, const char *str2, char* str3);
int stringLength(char * str);
int stringLength(char * str){
int len = 0;
while(*str != '\0'){
len++;
str++;
}
return len;
}
void getCommon(const char *str1, const char *str2, char* str3) {
int len1, len2;
int i, j, k;
int max = 0;
int start = -1;
len1 = stringLength(str1);
len2 = stringLength(str2);
for (i = 0; i < len1; i++) {
for (j = 0; j < len2; j++) {
if (str1[i] == str2[j]) {
for (k = 0; (str1[i + k] == str2[j + k] && str1[i + k] != '\0'); k++);
if (max < k) {
max = k;
start = i;
}
}
}
}
if (start == -1) {
str3[0] = 0;
}
else {
memcpy(str3, &str1[start], max);
str3[max] = 0;
}
}
int main() {
char str1[MAXROOM]="";
char str2[MAXROOM]="";
char str3[MAXROOM] = "";
gets(str1);
gets(str2);
getCommon(str1, str2, str3);
printf("%d\n", strlen(str3));
return 0;
}