求最大公共子串
阿新 • • 發佈:2018-12-10
#include <stdio.h> #include <string.h> int main1() { char *str1 = "aocdfe"; char *str2 = "aadapmcdfa"; int longest = 0; // 最大長度 int i,j; int start = 0; for (i = 0; i < strlen(str1); i++) { for (j = 0; j < strlen(str2); j++) { int len = 0; if (str1[i] == str2[j]) { int a, b; for (a = i, b = j; a<strlen(str1) && b<strlen(str2); a++, b++) { if (str1[a] == str2[b]) len++; else break; } } if (len > longest) { longest = len; start = i; } } } for (i = start; i < longest+start; i++) printf ("%c", str1[i]); printf ("\n"); return 0; } int main() { char *str1 = "aodacdfe"; char *str2 = "aadapmcdfea"; int table[100][100] = {0}; int i; int j; for (i = 0; i < strlen(str2); i++) { if (str1[0] == str2[i]) table[0][i] = 1; else table[0][i] = 0; } for (i = 1; i < strlen(str1); i++) { if (str2[0] == str1[i]) table[i][0] = 1; else table[i][0] = 0; for (j = 1; j < strlen(str2); j++) { if (str1[i] == str2[j]) { table[i][j] = table[i-1][j-1] + 1; } else { table[i][j] = 0; } } } int start = 0; int longest = table[0][0]; for (i = 1; i < strlen(str1); i++) { for (j = 1; j < strlen(str2); j++) { if (longest < table[i][j]) { longest = table[i][j]; start = i - longest + 1; } } } printf ("最大長度是:%d\n", longest); for (i = start; i < longest+start; i++) { printf ("%c", str1[i]); } printf ("\n"); return 0; }