• 1143. Longest Common Subsequence (Solution 3)


    /**
     * 1143. Longest Common Subsequence
     * https://leetcode.com/problems/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.
    
    Constraints:
    1 <= text1.length <= 1000
    1 <= text2.length <= 1000
    The input strings consist of lowercase English characters only.
     * */
    class Solution {
        fun longestCommonSubsequence(text1: String, text2: String): Int {
           val dp = Array(m + 1) { IntArray(n + 1) { -1 } }
            return dp2(text1, text2, m, n, dp)
        }
        
       /*
        * solution 2: DP: Memorization, Top-Down; Time complexity(mn), Space complexity:O(mn)
        * */
        private fun dp2(str1: String, str2: String, m: Int, n: Int, dp: Array<IntArray>): Int {
            if (m == 0 || n == 0) {
                return 0
            }
            if (dp[m][n] >= 0) {
                return dp[m][n]
            }
            var ans = 0
            if (str1[m - 1] == str2[n - 1]) {
                ans = 1 + dp2(str1, str2, m - 1, n - 1, dp)
            } else {
                ans = Math.max(dp2(str1, str2, m - 1, n, dp), dp2(str1, str2, m, n - 1, dp))
            }
            dp[m][n] = ans
            return ans
        }
    }
  • 相关阅读:
    HITCON Training lab14 magic heap 堆技巧unsroted bin attack
    堆技巧Unsorted Bin Attack
    2014-hack-lu-oreo 堆技巧house of spirit
    极客时间JVM虚拟机
    堆技巧 housr_of_spirit 绕过检查源码分析
    babyheap_0ctf_2017 堆技巧 fastbin-attack
    gyctf_2020_borrowstack wp
    SqlServer Where后面Case When语句的写法
    EasyUI TextBox的onkeypress事件
    SQL
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13604872.html
Copyright © 2020-2023  润新知