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

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

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

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;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值