代码随想录:最长公共子序列

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        // 和上一题的区别是,上一题必须连续,这题不需要
        vector<vector<int>> dp = vector<vector<int>>(
            text1.length() + 1, vector<int>(text2.length() + 1, 0));
        for (int i = 1; i <= text1.length(); i++) {
            for (int j = 1; j <= text2.length(); 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[text1.length()][text2.length()];
    }
};
posted @ 2025-02-28 16:44  huigugu  阅读(4)  评论(0)    收藏  举报