Question
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.
Moving owned classic problem, the longest common subsequence (LCS), note the sequence instead of a substring
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.
Dynamic Programming
To determine the state (or sub-optimal structure), c (i, j) represents the length of the longest common subsequence front str1 str2 i-th character, and the first j characters in
As an example may be thinking to write the state transition equation:
当 str1[i] == str2[j],c(i, j) = c(i-1, j-1) + 1
当 str1[i] != str2[j],c(i, j) = max(c(i, j-1), c(i-1, j))
When i == 0 or j == 0, the if str1 [i] == str2 [j ], c (i, j) = 1;! Str1 [i] = str2 [j], c (i, j) = 0 (boundary condition)
(This is the "or" instead of "and" very important, first wrote when he made a mistake)
In str1 = "ABCBDAB", str2 = "BDCABA" example to illustrate the sequence of enumeration
Arrows indicate the "source", and therefore can fill in order from top to bottom, left to right
From the figure, the boundary conditions are not just the top left corner, but the leftmost one side and a top side
(In fact, my algorithm and this figure is different, this figure will index = 0 represents an empty string, while my algorithm will index = 0 indicates the first character)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: len_1 = len(text1) len_2 = len(text2) dp = [[0 for j in text2] for i in text1] for i in range(len_1): for j in range(len_2): if (i == 0 or j == 0) and text1[i] == text2[j]: dp[i][j] = 1 elif text1[i] == text2[j]: dp[i][j] = dp[i-1][j-1] + 1 else: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) # print(dp[i][j], text1[i], text2[j]) return dp[len_1-1][len_2-1]
The time complexity is O (n * m)