最长公共子序列问题

DESC1:

给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。

一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。

若这两个字符串没有公共子序列,则返回 0。

示例 1:

输入:text1 = "abcde", text2 = "ace"
输出:3  
解释:最长公共子序列是 "ace",它的长度为 3。

示例 2:

输入:text1 = "abc", text2 = "abc"
输出:3
解释:最长公共子序列是 "abc",它的长度为 3。

示例 3:

输入:text1 = "abc", text2 = "def"
输出:0
解释:两个字符串没有公共子序列,返回 0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

CODE:

JAVA:

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        if (text1 == null || text2 == null || text1.length() == 0 || text2.length() == 0) {
            return 0;
        }
        int m = text1.length();
        int n = text2.length();
        int[][] dp = new int[m+1][n+1];
        for (int i=0; i<m+1; i++) {
            for (int j=0; j<n+1; j++) {
                if (i==0 || j==0) {
                    dp[i][j] = 0;
                    continue;
                }
                if (text1.charAt(i-1) == text2.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
                }
            }
        }
        return dp[m][n];
    }
}

Python

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        if not text1 or not text2 or len(text1)==0 or len(text2)==0:
            return 0
        m = len(text1)
        n = len(text2)
        dp = [[0]*(n+1) for i in range(m+1)]
        res = 0
        for i in range(1, m+1):
            for j in range(1, n+1):
                if text1[i-1] == text2[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                    res = max(res, dp[i][j])
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        return res

NOTES:

  1. 动态规划
  2. 思想:如果s1[i]=s2[j],则对于[0,i]和[0,j]区间字符序列,最大序列长度则只需要计算[0,i-1]和[0,j-1]区间的最大序列长度,然后加1就可;如果s1[i]!=s2[j], 则最大序列长度出现在两种情况:a.去除s1[i],计算s1[0,i-1]和s2[0,j]的长度; b.或者去除s2[j],计算1[0,i]和s2[0,j-1]的长度,两种取其大。因为s[i]和s[j]虽然不相等,但可能其一会和前面的元素组成最大序列。
  3. 体现在公式上:s1[i]==s2[j] ? dp[i][j] = dp[i-1][j-1]+1 : max(dp[i-1][j], dp[i][j-1])

稍微调整需求。。。

DESC2:

题目描述

给定两个字符串str1和str2,输出连个字符串的最长公共子序列。如过最长公共子序列为空,则输出-1。

示例1

输入

"1A2C3D4B56","B1D23CA45B6A"

返回值

"123456"

说明

"123456"和“12C4B6”都是最长公共子序列,任意输出一个。

备注:

1≤∣str1∣,∣str2∣≤5 0001 \leq |str_1|, |str_2| \leq 5\,0001≤∣str1​∣,∣str2​∣≤5000

CODE:

JAVA:

import java.util.*;


public class Solution {
    /**
     * longest common subsequence
     * @param s1 string字符串 the string
     * @param s2 string字符串 the string
     * @return string字符串
     */
    public String LCS (String s1, String s2) {
        // write code here
        int len1 = s1.length();
        int len2 = s2.length();
        if (len1 == 0 || len2 == 0) {
            return "-1";
        }
        int[][] dp = new int[len1 + 1][len2 + 1];
        for (int i = 0; i < len1+1; i++) {
            for (int j = 0; j < len2+1; j++) {
                if (i == 0 || j == 0) {
                    dp[i][j] = 0;
                    continue;
                }
                if (s1.charAt(i-1) == s2.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]);
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        while (len1!=0 && len2!=0) {
            if (s1.charAt(len1-1) == s2.charAt(len2-1)) {
                sb.append(s1.charAt(len1-1));
                len1--;
                len2--;
            } else if (dp[len1-1][len2] >= dp[len1][len2-1]) {
                len1--;
            } else {
                len2--;
            }
        }
        if (sb.length() == 0) {
            return "-1";
        }
        return sb.reverse().toString();
    }
}

NOTES:

  1. 基于需求一,我们得到了dp[i][j],表征着到s1[0,i]和s2[0,j]区间的最大序列数
  2. 通过倒序对比s1,s2尾部元素是否相同,借助dp数据,可根据最大值方向依次找到最长路径上的各个公共点,最后结果反转即可
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值