leetcode

1143.最长公共子序列

力扣链接

class Solution
{
public:
    int longestCommonSubsequence(std::string text1, std::string text2)
    {
        int len1 = text1.size(), len2 = text2.size();
        std::vector<std::vector<int>> dp(len1 + 1, std::vector<int>(len2 + 1));

        for (int i = 1; i < len1 + 1; i++)
            for (int j = 1; j < len2 + 1; j++)
            {
                if (text1[i - 1] == text2[j - 1]) // 为什么不是 if (text1[i] == text2[j])
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                else
                    dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]);
            }
        return dp[len1][len2];
    }
};