最长公共字串和最长公共子序列

本文介绍了解决最长公共子串与最长公共子序列问题的动态规划算法实现。通过构建二维矩阵来记录字符串之间的匹配情况,最终找出最长公共子串及子序列的长度。

LintCode 最长公共字串

给出两个字符串,找到最长公共子串,并返回其长度。

建立一个矩阵来保存两个字符串出现相同字符的地方,比如“abccd”和“abcefc”就有

abccd

a10000

b02000

c00300

e00040

f00000

c00100

这样就有每次遇到相等的都加上下他的斜上方的位置的值,然后使用一个max变量来记录目前的最大值即可

public class Solution {
    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
    public int longestCommonSubstring(String A, String B) {
        // write your code here
        char[] as = A.toCharArray();
        char[] bs = B.toCharArray();
        int[][] f = new int[bs.length][as.length];
        int max = 0;
        for(int i = 0; i < bs.length; i++){
            for(int j =0; j < as.length; j++){
                int pre = (i-1 >= 0 && j-1 >= 0)?f[i-1][j-1]:0;
                if(bs[i] == as[j]){
                    f[i][j] = 1+pre;
                    max = Math.max(f[i][j],max);
                }
            }
        }
        return max;
    }
}


LintCode 最长公共子序列

给出两个字符串,找到最长公共子序列(LCS),返回LCS的长度。

这个题和最长公共字串的区别就在于公共字串必须是连着的,但是这个可以不连着!

对于公共子序列其实也是要建立一个m*n的矩阵A来记录当前的最长子序列的长度,但是矩阵更新的规则变成:


public class Solution {
    /**
     * @param A, B: Two strings.
     * @return: The length of longest common subsequence of A and B.
     */
    public int longestCommonSubsequence(String A, String B) {
        // write your code here
        char[] as = A.toCharArray();
	        char[] bs = B.toCharArray();
	        int[][] f = new int[bs.length][as.length];
	        int max = 0;
	        for(int i = 0; i < bs.length; i++){
	            for(int j = 0; j < as.length; j++){
	                int pre = (i-1 >= 0 && j-1 >= 0)?f[i-1][j-1]:0;
	                if(bs[i] == as[j]){
	                    f[i][j] = 1 + pre;
	                }
	                else
	                	f[i][j] = Math.max(i-1>=0? f[i-1][j]:0,j-1>=0?f[i][j-1]:0);
	                  max = Math.max(f[i][j], max);
	            }
	        }
	        return max;
    }
}



### C++ 实现最长公共子串最长公共子序列的暴力算法 #### 最长公共子串的暴力求解方法 以下是基于暴力枚举的方法来寻找两个字符串之间的最长公共子串: ```cpp #include <iostream> #include <vector> #include <string> using namespace std; void findLongestCommonSubstring(const string& s1, const string& s2) { int maxLength = 0; string result = ""; for (int i = 0; i < s1.length(); ++i) { for (int j = 0; j < s2.length(); ++j) { int k = 0; while ((i + k) < s1.length() && (j + k) < s2.length() && s1[i + k] == s2[j + k]) { k++; } if (k > maxLength) { maxLength = k; result = s1.substr(i, k); } } } cout << "最长公共子串为:" << result << endl; } int main() { string str1 = "cnblogs"; string str2 = "belong"; findLongestCommonSubstring(str1, str2); return 0; } ``` 此代码通过双重循环遍历 `s1` `s2` 的每一个位置,尝试匹配从当前位置开始的最大相同部分[^2]。 --- #### 最长公共子序列的暴力求解方法 对于最长公共子序列问题,可以使用递归来穷尽所有可能性并找到最优解。以下是一个简单的暴力实现方式: ```cpp #include <iostream> #include <string> using namespace std; // 辅助函数用于计算LCS长度 int lcsLength(string X, string Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcsLength(X, Y, m - 1, n - 1); else return max(lcsLength(X, Y, m, n - 1), lcsLength(X, Y, m - 1, n)); } // 主程序入口 int main() { string str1 = "cnblogs"; string str2 = "belong"; int length = lcsLength(str1, str2, str1.length(), str2.length()); cout << "最长公共子序列的长度为:" << length << endl; return 0; } ``` 该代码的核心在于递归地判断当前字符是否相等,并分别处理三种情况:继续向前探索、跳过第一个字符串中的字符或者跳过第二个字符串中的字符[^1]。 --- ### 结果分析 - **最长公共子串**的结果依赖于连续性条件,在上述例子中会输出 `"lo"`。 - **最长公共子序列**则不需要考虑连续性,因此其结果可能是 `"blog"` 或其他符合条件的组合[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值