1143. Longest Common Subsequence

梦想的初衷 提交于 2020-01-06 13:20:38

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!