The longest common subsequence of LeetCode dynamic programming

Get into the habit of writing together! This is the 7th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

topic

Given two strings  text1and  text2, return the length of the longest common subsequence of the two strings. Returns if no common subsequence exists 0.

A subsequence of a string is a new string consisting of some characters (or none of them) removed from the original string without changing the relative order of the characters.

For example, "ace"is "abcde"a subsequence of , but "aec"is not "abcde"a subsequence of . The common subsequence of two strings is the subsequence that both strings have in common.

Example 1:

输入:text1 = "abcde", text2 = "ace" 
输出:3  
复制代码

Explanation: The longest common subsequence is "ace", its length is 3.

Example 2:

输入:text1 = "abc", text2 = "abc"
输出:3
复制代码

Explanation: The longest common subsequence is "abc", its length is 3.

Example 3:

输入:text1 = "abc", text2 = "def"
输出:0
复制代码

Explanation: The two strings have no common subsequence, return 0.  

hint:

1 <= text1.length, text2.length <= 1000
text1 和 text2 仅由小写英文字符组成。
复制代码

answer

problem-solving analysis

Problem solving ideas:

  1. The longest common subsequence problem is a typical two-dimensional dynamic programming problem.
  2. The state transition equation is as follows:
// text1.charAt(i - 1) == text2.charAt(j - 1)
dp[i][j] = dp[i - 1][j - 1] + 1;
// text1.charAt(i - 1) != text2.charAt(j - 1)
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
复制代码
  1. the final return result dp[m][n];

Complexity:
Time Complexity: O(M*N)
Space Complexity:O(M*N)

problem solving code

The solution code is as follows (detailed comments in the code):


class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
            // 获取长度
            int m = text1.length(), n = text2.length();
            // 创建 dp
            int[][] dp = new int[m + 1][n + 1];
            for (int i = 1; i <= m; i++) {
                char c1 = text1.charAt(i - 1);
                for (int j = 1; j <= n; j++) {
                    char c2 = text2.charAt(j - 1);
                    if (c1 == c2) {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                    } else {
                        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                    }
                }
            }
            return dp[m][n];
    }
}
复制代码

Feedback results after submission (because this topic has not been optimized, the performance is average):

image.png

Reference Information

Guess you like

Origin juejin.im/post/7084200685801046029