您的位置:首页 > 其它

Maximum Length of Repeated Subarray

2017-11-11 22:26 519 查看
问题描述:

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

给定两个数组A、B,返回两个数组中的最大相同子数组的长度

问题解决:

用二维数组a[i][j]储存

通过动态规划找到A数组到i为止,B数组到j为止的最大相同字数组的长度,那么a[i][j]的递推式可以表示为

若A[i]==B[j]  a[i][j] = a[i-1][j-1] + 1

否则a[i][j] = 0

代码如下:

class Solution {

public:

    int findLength(vector<int>& A, vector<int>& B) {

        int i, j;

        int max = 0;

        int len1 = A.size();

        int len2 = B.size();

        int a[1001][1001];

        //初始化数组

        for(i = 0; i < 1001; i++) {

            for(j = 0; j < 1001; j++) {

                a[i][j] = 0;

            }

        }

        //根据递推式算出子问题的值

        for(i = 1; i < len1+1; i++) {

            for(j = 1; j < len2+1; j++) {

                a[i][j] = A[i-1] == B[j-1] ? a[i-1][j-1] + 1 : 0;

                //找到最大的长度

                max = max > a[i][j] ? max : a[i][j];

            }

        }

        return max;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: