原创文章,转载请注明出处!
问题:
求A和B两个字符串的最长公共子串,并输出其长度。
分析:
我还没看过系统算法方面的书,不过我想以后要加强了,:-),目前我想到用“平移法”来计算最长公有串,还未分析过其它算法,不过我想,这个速度应该还不错。
原理:把两个字符串想像成两板木板,木板A短于木板B,让木板A在木板B上平移,从而找到垂直方向的公共字符串,进尔求得最长公有串
分解1
+-------------+ | A | +-------------+ +---------------------+ | B | +---------------------+ ^ i
分解2
+-------------+ | A | +-------------+ +---------------------+ | B | +---------------------+ ^ i代码实现:
#include "stdafx.h" #include <iostream> using namespace std; void get_substr(char* strA, char* strB, char* strSub); int _tmain(int argc, _TCHAR* argv[]) { char* a = "hello, i am =weisunding!"; char* b ="my name is -weisunding, you who??"; char substr[100] = {0}; get_substr(a, b, substr); cout<<substr<<endl; system("pause"); return 0; } //核心代码 void get_substr(char* strA, char* strB, char* strSub) { int sub_index = 0; int sub_len = 0; // strlen(s1) < strlen(s2) char* s1 = strA; char* s2 = strB; if (strlen(strA) > strlen(strB)) swap(s1, s2); int len1 = strlen(s1); int len2 = strlen(s2); int x1,x2; for(int i = 1 - len1; i < len2; ++i) { if (i <= 0) { x1 = i + len1 - 1; x2 = 0; } else { x1 = 0; x2 = i;
if (len2 - x2 < sub_len)
break; } int len = 0; while( (x1 < len1) || (x2 < len2)) { if ( s1[x1] == s2[x2]) { ++len; if (len > sub_len) { sub_index = x2; //the last index sub_len = len; } } else { len = 0; } ++x1; ++x2; } } if (sub_len) strncpy(strSub, s2 + sub_index - (sub_len - 1) , sub_len); }