leetCode(Using C)——718. Maximum Length of Repeated Subarray

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lovefengruoqing/article/details/79051266

Description:

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

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

If you want to solve the problem, you can visite the web site.click me

Solution

采用动态规划的思路

#ifndef MAX(X,Y)
#define MAX(X,Y) (((X)>(Y))?(X):(Y))    //定义三目运算符
#endif // MAX

int findLength(int *A, int ASize, int *B, int BSize){
    int Count[ASize+1][BSize+1];   //设立而为Count数组
    int i,j,max=0;
    memset(Count, 0, sizeof(Count));  //重置数组空间
    for(i=1;i<ASize+1;i++){
        for(j=1;j<BSize+1;j++){
            Count[i][j]=A[i-1]==B[j-1]?Count[i-1][j-1]+1:0;   //依次根据上一行改变当前行的统计长度
            max=MAX(Count[i][j],max);   //记录遇到的最大值
        }
    }
    return max;
}

猜你喜欢

转载自blog.csdn.net/lovefengruoqing/article/details/79051266