求两个字符串共同子串的长度
程序员文章站
2024-02-26 15:35:22
...
给定两个字符串,找出最长的共同子串,返回它的长度。
例如:A="ABCD", B="CBCE",返回2.
注意:在substring中的字符应当在原string中连续。而subsequence不是连续的。
int longCommonSubstring(string& A,string&B)
{
if(A.empty() || B.empty())
{
return 0;
}
int lcs = 0;
int lcs_tmp;
for(int i=0;i<A.size();i++)
{
for(int j=0;j<B.size();j++)
{
lcs_tmp = 0;
while((i+lcs_tmp < A.size())&& \
(j+lcs_tmp < B.size())&& \
(A[i+lcs_tmp] == B[j+lcs_tmp]))
{
++lcs_tmp;
}
if(lcs_tmp > lcs)
{
lcs = lcs_tmp;
}
}
}
return lcs;
}
上一篇: API常用类-StringBuffer类
下一篇: Struct和Union的区别