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

純愛楓若情發表於2018-01-13

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;
}

相關文章