• 【leetcode】1143. Longest Common Subsequence


    题目如下:

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

    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.
    

    Example 2:

    Input: text1 = "abc", text2 = "abc"
    Output: 3
    Explanation: The longest common subsequence is "abc" and its length is 3.
    

    Example 3:

    Input: text1 = "abc", text2 = "def"
    Output: 0
    Explanation: There is no such common subsequence, so the result is 0.
    

    Constraints:

    • 1 <= text1.length <= 1000
    • 1 <= text2.length <= 1000
    • The input strings consist of lowercase English characters only.

    解题思路:典型的动态规划场景。记dp[i][j]为text1的[0~i]区间,text2[0~j]区间内最长的公共子序列的长度。那么显然有: 如果 text1[i] == text2[j],dp[i][j] = max(dp[i][j],dp[i-1][j-1]+1);又如果 text1[i] != text2[j],有 dp[i][j] = max(dp[i][j],dp[i-1][j-1],dp[i-1][j],dp[i][j-1])。

    代码如下:

    class Solution(object):
        def longestCommonSubsequence(self, text1, text2):
            """
            :type text1: str
            :type text2: str
            :rtype: int
            """
            dp = [[0]* len(text2) for _ in text1]
            for i in range(len(text1)):
                for j in range(len(text2)):
                    if text1[i] == text2[j]:
                        dp[i][j] = 1
                        if i > 0 and j > 0:
                            dp[i][j] = max(dp[i][j],1+dp[i-1][j-1])
                    else:
                        if i > 0 and j > 0:
                            dp[i][j] = max(dp[i][j],dp[i-1][j-1])
                        if i > 0:
                            dp[i][j] = max(dp[i][j],dp[i-1][j])
                        if j > 0:
                            dp[i][j] = max(dp[i][j],dp[i][j-1])
            #print dp
            return dp[-1][-1]
  • 相关阅读:
    渚漪Day18——JavaWeb 09【JSP】
    渚漪Day17——JavaWeb 08【Session】
    渚漪Day16——JavaWeb 07【Cookie】
    渚漪Day15——JavaWeb 06【HTTPServletRequest】
    渚漪Day14——JavaWeb 05【HTTPServletResponse】
    Typora编写markdown 常用入门
    Vue 笔记
    ABCNN 学习笔记
    DSSM 学习笔记
    支持向量机 SVM 学习笔记
  • 原文地址:https://www.cnblogs.com/seyjs/p/11308342.html
Copyright © 2020-2023  润新知