leetcode1143最长公共子序列

先定义dp[i][j]是第一个字符串的i位置和第二个字符串j位置之前最长的公共子序列数目。返回的时候返回dp[lenA][lenB

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int dp[1005][1005];
        int i;
        for(i=0;i<text1.length();i++)
        {
            dp[i][0]=0;
        }
        for(i=0;i<text2.length();i++)
        {
            dp[0][i]=0;
        }
        int j;
        for(i=1;i<=text1.length();i++)
        {
            for(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()];
    }
};

]

猜你喜欢

转载自www.cnblogs.com/legendcong/p/12528174.html