1143. Longest Common Subsequence
Posted beatets
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1143. Longest Common Subsequence相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
1143. Longest Common Subsequence
LeetCode 1143. Longest Common Subsequence
leetcode1143 Longest Common Subsequence
算法:最长子序列1143. Longest Common Subsequence