leetcode 1143.最长公共子序列(Java)

  1. Longest Common Subsequence
    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.

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        //字符串为null或长度为0,不可能有公共部分
        if(text1 == null || text1.length() == 0) return 0;
        if(text2 == null || text2.length() == 0) return 0;
        //动态规划,考虑到0到i的text1和0到j长度的text2取最大公共子序列,如果text1.charAt(i) == text2.charAt(j), 取0到i-1的text1子串和0到j-1的text2子串的最大公共子序列值+1,如果不等,那就直接取这个最大公共子序列长度
        int len1 = text1.length(), len2 = text2.length();
        int[][] dp=new int[len1+1][len2+1];
        //还是要把i=0和j=0的情况先写完
        for(int i=0;i<len1+1;i++){
            dp[i][0] = 0; //text2为空
        }
        for(int j=0;j<len2+1;j++){
            dp[0][j] = 0; //text1为空
        }

        for(int i=1;i<len1+1;i++){
            for(int j=1;j<len2+1;j++){
                if(text1.charAt(i-1) == text2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1]+1;
                }else{
                    //这里要取单独减一的最大值,因为dp[i-1][j]和dp[i][j-1]一定大于等于dp[i-1][j-1]
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }

        return dp[len1][len2];

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值