LCS/最长公共子串算法分析

最长公共子串算法详解
本文介绍了最长公共子串(LCS)问题,探讨了基于穷举法的解法及其时间复杂度,并详细阐述了使用动态规划法的空间优化策略,包括状态转移方程和临界情况处理。此外,还提到了进一步的优化以及广义后缀树方法,但表示对后者的理解尚不深入。

最长公共子串

一、最长公共子串(Longest Common Substring ,简称LCS)问题,是指求给定的一组字符串长度最大的共有的子串的问题。例如字符串"abcb","bca","acbc"的LCS就是"bc"。

求多串的LCS,显然穷举法是极端低效的算法。直观的思路就是问题要求什么就找出什么。要子串,就找子串;要相同,就比较每个字符;要最长就记录最长。所以很容易就可以想到如下的解法。

 

//暴力求解法 
int longestCommonSubstring_n3(const string& str1, const string& str2)
{   
    size_t size1 = str1.size();
    size_t size2 = str2.size();
    if (size1 == 0 || size2 == 0) return 0;
 
    // the start position of substring in original string
    int start1 = -1;
    int start2 = -1;
    // the longest length of common substring 
    int longest = 0; 
 
    // record how many comparisons the solution did;
    // it can be used to know which algorithm is better
    int comparisons = 0;
 
    for (int i = 0; i < size1; ++i)
    {
        for (int j = 0; j < size2; ++j)
        {
            // find longest length of prefix 
            int length = 0;
            int m = i;
            int n = j;
            while(m < size1 && n < size2)
            {
                ++comparisons;
                if (str1[m] != str2[n]) break;
 
                ++length;
                ++m;
                ++n;
            }
 
            if (longest < length)
            {
                longest = length;
                start1 = i;
                start2 = j;
            }
        }
    }
#ifdef IDER_DEBUG
    cout<< "(fi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值