Longest common substring

本文介绍了一种寻找两个字符串间最长公共子串的算法。通过逐步减少子串长度并检查是否存在,最终找到最长的公共子串。代码示例展示了如何实现这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我这里所说的longest common substring问题和算法导论中的不一样,主要是找出连续的最长子序列。

输入:string S1,S2

输出:所有连续的最长子序列

 

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

void Pre_Process(string P, int* pi)
{
    
int m=P.size();
    pi[
0]=0;
    
int j=0;
    
int i;

    
for(i=1;i<m;++i)
    
{
        
while(j>0&&(P[j]!=P[i]))
            j
=pi[j-1];
        
if(P[j]==P[i])
            
++j;
        pi[i]
=j;
    }

}


bool Check(string S,string P)
{
    
int n=S.size();
    
int m=P.size();
    
int* pi=new int[m];
    Pre_Process(P,pi);

    
int q=0;
    
int i;
    
for(i=0;i<n;++i)
    
{
        
while(q>0&&(P[q]!=S[i]))
            q
=pi[q-1];
        
if(P[q]==S[i])
            
++q;
        
if(q==m)
                                            
{
                                                                delete[] pi;
            
return true;
                                             }

    }


                     delete[] pi;
    
return false;
}


void find_LCS(string S1,string S2)
{
    
int len=S2.size();
    
int step=len;
    
bool flag=false;
    
while(step>=0)
    
{
        
int i;
        
for(i=0;i<=len-step;++i)
        
{
            
string temp(S2, i, step);
            
if(Check(S1,temp))
            
{
                cout
<<temp<<endl;
                flag
=true;
            }

        }

        
if(flag)
        
{
            cout
<<"the length of the longest common substring is:"<<step<<endl;
            
break;
        }

        
else
            
--step;
    }

}


void LCS(string S1,string S2)
{
    
if(S1.size()<S2.size())
        find_LCS(S2,S1);
    
else
        find_LCS(S1,S2);
}




int main()
{
                     
string S1("hello world");
                     
string S2("world,hello");

                      LCS(S1,S2);



    
return 0;
}

输出结果为:

world
hello
the length of the longest common substring is:5
Press any key to continue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值