zoukankan      html  css  js  c++  java
  • 【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]
  • 相关阅读:
    关于 web service 参数传递的序列化反序列化问题
    (转)GIS理论(墨卡托投影、地理坐标系、地面分辨率、地图比例尺、Bing Maps Tile System)
    (转)如何oracle调试存储过程
    word中字号和磅数的对应
    (转)C# 泛型相关讲解
    16 款最流行的 JavaScript 框架(转)
    mark:about 手势
    UIWebView
    android 无法安装ApiDemos
    Android开发中的单元测试
  • 原文地址:https://www.cnblogs.com/seyjs/p/11308342.html
Copyright © 2011-2022 走看看