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

1143. Longest Common Subsequence

时间:2020-01-06 09:54:55      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:hat   esc   ext   ret   tar   enc   href   long   none   

link to problem

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.

 

Solution:

 1 class Solution:
 2     def longestCommonSubsequence(self, text1: str, text2: str) -> int:
 3         
 4         n1 = len(text1)
 5         n2 = len(text2)
 6         
 7         dp = [[0 for i in range(n2+1)] for j in range(n1+1)]
 8         for i in range(n1):
 9             for j in range(n2):
10                 if text1[i]==text2[j]:
11                     dp[i][j] = 1 + dp[i-1][j-1]
12                 else:
13                     dp[i][j] = max(dp[i-1][j], dp[i][j-1])
14         
15         return dp[n1-1][n2-1]

 

Notes:

2-d Dynamic Programming

O(mn)

1143. Longest Common Subsequence

标签:hat   esc   ext   ret   tar   enc   href   long   none   

原文地址:https://www.cnblogs.com/beatets/p/12154648.html

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