美文网首页Leetcode
leetCode_718. Maximum Length of

leetCode_718. Maximum Length of

作者: DDB_CS | 来源:发表于2017-11-02 18:59 被阅读37次

    Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

    题目意思是给定两个整型数组A和B,返回两个数组的公共子串的最大长度。
    样例输入如下:

    Example 1:
    Input:
    A: [1,2,3,2,1]
    B: [3,2,1,4,7]
    Output: 3
    Explanation: 
    The repeated subarray with maximum length is [3, 2, 1].
    Note:
    1 <= len(A), len(B) <= 1000
    0 <= A[i], B[i] < 100
    

    题目意思很明确,最长公共子数组问题,LCS用动态规划做比较合适。
    取dp[i][j]表示A 数组到i位置,B数组到j位置时最长公共子数组长度,
    转移方程为:

         if(A[i-1]==B[j-1]) {
              dp[i][j] = dp[i-1][j-1]+1;
        }  else{
              dp[i][j] = 0;
        }
    

    然后用max变量记录最大的dp[i][j]
    代码如下:

    class Solution {
    public:
        int findLength(vector<int>& A, vector<int>& B) {
            
            int lenA = A.size();
            int lenB = B.size();
            vector<vector<int>> dp(lenA+1,vector<int>(lenB+1,0)); // 初始化数组为0
            
            int max = 0; // 记录最大长度
            
            for (int i = 1;i <= lenA ;i ++) {
                for (int j = 1;j<=lenB;j ++) {
                    if(A[i-1] ==  B[j-1]) {
                        dp[i][j] = dp[i-1][j-1] + 1;
                        if(dp[i][j] > max) max = dp[i][j];
                    }else {
                        dp[i][j] = 0;
                    }
                }
            }
            return max; 
        }
    };
    

    相关文章

      网友评论

        本文标题:leetCode_718. Maximum Length of

        本文链接:https://www.haomeiwen.com/subject/lvsapxtx.html