求公共子串问题

算法思想来自:http://blog.csdn.net/shaohui/archive/2006/06/09/784577.aspx

//  求两字符串最大公共子串 from: http://blog.csdn.net/shaohui/archive/2006/06/09/784577.aspx
/*
s1 = "abcdefg", s2 = "klmncdf"
 abcdefg         | abcdefg        | abcdefg       | abcdefg
        klmncdf  |       klmncdf  |      klmncdf  |     klmncdf
s1慢慢滑过s2

*/

#include
< iostream >
#include
< string >
using   namespace  std;

//  返回最大公共子串长度
int  bigsubstring( const   string   & str1,  const   string   & str2)
{
    
int len1 = str1.length(), len2 = str2.length(), len = len1 + len2;
    
int cnt, idx; // 迭代量
    int curmax, max; // curmax:当前公共子串最大长度,max:要返回的最大公共子串长度
    int s1start, s2start; // 两字符串开始遍历的位置

    max 
= 0;
    
for(cnt = 0; cnt < len; ++cnt)
    
{
        s1start 
= 0;
        s2start 
= 0;

        
if(cnt < len1)
            s1start 
= len1 - cnt;
        
else
            s2start 
= cnt - len1;

        curmax 
= 0;
        
for(idx = 0; (s1start + idx < len1) && (s2start + idx < len2); ++idx)
        
{
            
if(str1[s1start + idx] == str2[s2start + idx])
                curmax
++;
            
else
            
{
                max 
= (curmax > max) ? curmax : max;
                curmax 
= 0;
            }

        }


        max 
= (curmax > max) ? curmax : max;
    }
 // 1st for

    
return max;
}


int  main()
{
    
string s1, s2;

    cin 
>> s1 >> s2;

    cout 
<< bigsubstring(s1, s2) << endl;

    
return 0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值