leetcode 1143. 最长公共子序列-华为

思路

代码:

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        if(text1.size()==0||text2.size()==0)
        {
            return 0;
        }
        int dp[text1.length()+1][text2.length()+1];
        for (int i = 0;i<text1.length()+1;i++)
        {
            dp[i][0] = 0;
        }
        for(int j = 0;j<text2.length()+1;j++)
        {
            dp[0][j] = 0;
        }
        for(int i = 1;i<text1.length()+1;i++)
        {
            for(int j =1;j<text2.length()+1;j++)
            {
                if(text1[i-1]== text2[j-1]) //两个子串中有相等的字符 公共字符,计数+1
                {
                    dp[i][j] = dp[i-1][j-1]+1;
                }
                else
                {
                    dp[i][j] = max(dp[i][j-1],dp[i-1][j]); //否则不计数,保留上次最大的结果
                }
            }
        }
        return dp[text1.length()][text2.length()];
    }
};

 

posted @ 2021-09-26 16:33  A-inspire  Views(36)  Comments(0Edit  收藏  举报