LeetCode 1143. Longest Common Subsequence

Description:

Given two strings text1 and text2, return the length of their longest common subsequence.

A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, “ace” is a subsequence of “abcde” while “aec” is not). A common subsequence of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

Example 1:

Input: text1 = “abcde”, text2 = “ace”
Output: 3
Explanation: The longest common subsequence is “ace” and its length is 3.

Solution:

使用动态规划,对于每个可能的dp[i][j]组合,其转移方程如下:

dp[i][j] = dp[i - 1][j - 1] + 1; //当a.charAt(i) == b.charAt(j)
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); //当a.charAt(i) == b.charAt(j)

dp[i][j] 表示字符串a中第i个字符作为结尾和字符串b中第j个字符作为结尾的字符串最长公共子序列。当a.charAt(i) == b.charAt(j);最长子序列会增长一位。

java 代码如下:

public int longestCommonSubsequence(String a, String b) {
        int[][] dp = new int[a.length() + 1][b.length() + 1];

        for(int i = 1; i <= a.length(); ++i) {
            for(int j = 1; j <= b.length(); ++j) {
                if(a.charAt(i - 1) == b.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[a.length()][b.length()];
    }

把生成的dp矩阵打印如下:

0 0 0 0 0 0 0 
0 0 0 0 1 1 1 
0 1 1 1 1 2 2 
0 1 1 2 2 2 2 
0 1 1 2 2 3 3 
0 1 2 2 2 3 3 
0 1 2 2 3 3 4 
0 1 2 2 3 4 4 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值