两个字符串的最长公共子序列和最长公共子字符串的问题

       求解两个字符串的公共最长子序列,在面试中经常出现。这里,我们来用C++实现其功能。关于理论知识,这篇文章已经写的非常好:https://www.cnblogs.com/hapjin/p/5572483.html,在这里我不在描述。下面,我们直接来给出C++代码实现:

//两个字符串的最长公共子序列:动态规划
string get_same(string str1, string str2)
{
    int length1 = str1.length();
    int length2 = str2.length();
    int lcs[length1+1][length2+1];
    memset(lcs,0,sizeof(lcs));
    for(int i = 1; i <= length1; i++)
        for(int j = 1; j <= length2; j++)
        {
            if (str1[i-1] == str2[j-1])
                lcs[i][j] = lcs[i-1][j-1] + 1;//由于下标是从1开始,因此,实际表示的内容为lcs[i][j]表示的是字符串str1[0:i-1]与字符串str2[0:j-1];
            else
                lcs[i][j] = max(lcs[i-1][j],lcs[i][j-1]);
        }
    return lcs[length1][length2];
}

//最长公共子序列:递归
string str1,str2;
string lcs(int len1, int len2)
{
    if (len1 == -1 || len2 == -1)
        return 0;
    else if (str1[len1] == str2[len2])
        return lcs(len1-1, len2-1) + 1;
    else
        return lcs(len1-1,len2)>lcs(len1,len2-1)?lcs(len1-1,len2):lcs(len1,len2-1);
}

同样,两个字符串的最长公共子字符串也是面试的重点,我们接下来讨论该问题:

在这篇文章中http://www.360doc.com/content/17/0217/14/10408243_629714477.shtml,理论知识简单明了。而在这篇文章中https://blog.csdn.net/u012102306/article/details/53184446,代码思路明确。接下来,是我们用C++来展示这个功能:

//两个字符串的公共子字符串
int max_same_str(string str1, string str2)
{
    int len1 = str1.length();
    int len2 = str2.length();
    int result = 0;
    int max_matrix[len1+1][len2+1];
    memset(max_matrix,0,sizeof(max_matrix));
    for (int i = 1; i <= len1; i++)
        for (int j = 1; j <= len2; j++)
        {
            if (str1[i-1] == str2[j-1])
            {
                max_matrix[i][j] = max_matrix[i-1][j-1]+1;
                result = max(max_matrix[i][j],result);
            }
            else
                max_matrix[i][j] = 0;

        }
    return result;
}

猜你喜欢

转载自blog.csdn.net/LiuPeiP_VIPL/article/details/81738535