首页 > 其他 > 详细

1143. Longest Common Subsequence

时间:2020-01-06 10:01:41      阅读:73      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!