### leetcode010-Maximum Length of Repeated Subarray(LCS動態規划)

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. 1 <= len(A), len(B) <= 1000
2. 0 <= A[i], B[i] < 100

狀態轉移 lengthEndsAtAB[i][j] = (A[i-1] == B[j-1]) ? lengthEndsAtAB[i-1][j-1]+1:0

2.一旦A[i-1] != B[j-1]即可設為0，因為最長的重復子串要求連續，如果當前位置已經發生中斷，則計數不會再從這個點開始增加。而在檢測到A的前i個字符，B的前j個字符的狀態時，當中能夠生成的最長重復子串的長度以被lengthEndsAtAB[i-1][j-1]所記錄。這個點必須設為0，否則會影響lengthEndsAtAB[i+1][j+1]的值。

```class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
vector<vector<int>> lengthEndsAtAB(A.size()+1,vector<int>(B.size()+1,0));
int result = 0;
for (int i = 1; i < lengthEndsAtAB.size(); i++) {
for (int j = 1; j < lengthEndsAtAB[0].size(); j++) {
lengthEndsAtAB[i][j] = A[i-1]==B[j-1] ? lengthEndsAtAB[i-1][j-1]+1:0;
result = lengthEndsAtAB[i][j] > result ? lengthEndsAtAB[i][j]:result;
}
}
return result;
}
};
```

```int longestSubstring(string x, string y) {
vector<vector<int>> max(x.size()+1,vector<int>(y.size()+1,0));
int result = 0;
for (int i = 1; i < x.size()+1; i++) {
for (int j = 1; j < y.size()+1; j++) {
max[i][j] = x[i-1]==y[j-1]?max[i-1][j-1]+1:0;
result = result<max[i][j]?max[i][j]:result;
}
}
return result;
}
```