码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1143. Longest Common Subsequence

时间:2019-08-06 14:01:01      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:gen   tco   ==   self   one   har   动态   Nging   题目   

题目如下:

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]

 

【leetcode】1143. Longest Common Subsequence

标签:gen   tco   ==   self   one   har   动态   Nging   题目   

原文地址:https://www.cnblogs.com/seyjs/p/11308342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!