• 1143.最长公共子序列


    给定两个字符串 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。

    思路:

      • 两层 for 循环,遍历两个字符串,每一次得到两个字符 c1, c2;
      • 当字符 c1 == c2 相等时,即 c1, c2 都存在于最终的公共子序列中,子序列长度 +1;
      • 否则,取 c1 存在,c2 不存在c1不存在, c2 存在 的两个子序列结果中,最长的那一个结果。

    class Solution {
        public int longestCommonSubsequence(String text1, String text2) {
            int m = text1.length(), n = text2.length();
            int[][] dp = new int[m+1][n+1];
            for(int i = 1; i <= m; i++){
                for(int j = 1; j <= n; j++){
                    char c1 = text1.charAt(i-1), c2 = text2.charAt(j-1);
                    if(c1 == c2) dp[i][j] = 1 + dp[i-1][j-1]; //字符相等
                    else dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]); //字符不相等
                }
            }
            return dp[m][n];
        }
    }
  • 相关阅读:
    Leetcode题目:Remove Duplicates from Sorted List
    Leetcode题目:Lowest Common Ancestor of a Binary Search Tree
    Leetcode题目:Ugly Number
    Leetcode题目:Remove Linked List Elements
    Leetcode题目:Count and Say
    6-3 事务
    6-1 视图
    5-2 pymysql模块
    5-1 图形工具Navicat
    4-3 多表查询
  • 原文地址:https://www.cnblogs.com/luo-c/p/13832810.html
Copyright © 2020-2023  润新知