程式設計實現查詢兩個字串的最大公共子串
阿新 • • 發佈:2018-12-10
#include <stdio.h> #include <string.h> //程式設計實現查詢兩個字串的最大公共子串 //示例:"aocdfe"和"pmcdfa"最大公共子串為"cdf" void MyPub(char *str1, char *str2) { char *p1=str1; char *p2=str2; int len1=strlen(str1); int len2=strlen(str2); char a[100] = {0};//存放公共子串 char b[100] = {0};//存放最大公共子串 char c[100] = {0}; int i; if(len2>len1) { strcpy(c, str1); strcpy(str1, str2); strcpy(str2, c); } for(i=0; i<len1; i++) { int sum = 0; if(*p1 == *p2) { while(*p1 == *p2) { a[sum]=*p2;//將子串賦給陣列a sum++; p1++; p2++; } } else p1++; if(strlen(a) > strlen(b))//找出最大子串 strcpy(b, a); sum=0; } printf("最大公共子串:%s\n", b); } int main() { char str1[100] = {0}; char str2[100] = {0}; printf("請輸入字串1:"); scanf("%s", str1); printf("請輸入字串2:"); scanf("%s", str2); MyPub(str1, str2); return 0; }