http://blog.csdn.net/hairetz/article/details/4664846 算法
最大公共子串算法可用動態規劃來解。數組
網上有篇是用一個一維數組(string,本質是一維)來記錄匹配信息。效果還能讓人滿意,貼出代碼與我的理解。spa
string lcs_search(string str1, string str2) .net
{ orm
if (str1.length() < str2.length()) //保證str1爲母串(較長的哪一個串) blog
{ get
string strTemp = str1; string
str1 = str2; it
str2 = strTemp; sdk
}
int * sign = new int[str1.length()]; //sign裏存儲的是母串(str1)每一個元素前向能與子串匹配的公共子串數
//好比sign[12]==5;則說明從str1[12]往前5個元素(包括[12]),能與str2的某一段匹配
int length = 0;
int end = 0;
for (int i = 0; i < str2.length(); i++)
{
for (int j = str1.length() - 1; j >= 0; j-- )
{
if (str2[i] == str1[j])
{
if (i == 0 || j == 0) //i==0,則母串的j元素必然只能匹配一個,j==0同理
sign[j] = 1;
else //因爲該次j匹配,因此子串能夠+1
sign[j] = sign[j - 1] + 1;
}
else //不匹配,則此位置的sign歸零
sign[j] = 0;
if (sign[j] > length) //結果存儲
{
length = sign[j];
end = j;
}
}
}
delete []sign;
return str1.substr(end - length + 1, length);
}
int main()
{
string a="123456789abcdefghijklmn2131.dfdfdf",b="123456sdkk123456789abcddkfdfkd123456789abcde";
string c;
c=lcs_search(a,b);
cout<<c<<endl;
return 0;
}