Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1143. Longest Common Subsequence

Rain Hu

1143. Longest Common Subsequence


一、題目

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. 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.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. DP

int longestCommonSubsequence(string text1, string text2) {
        int m = text1.length(), n = text2.length();
        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (text1[i-1] == text2[j-1])
                    dp[i][j] = dp[i-1][j-1] + 1;
                else
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        }
        return dp[m][n];
    }

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1235. Maximum Profit in Job Scheduling
Next
[LeetCode] 300. Longest Increasing Subsequence