Maximum Length of Repeated Subarray
2017-11-11 22:26
519 查看
问题描述:
Given two integer arrays
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;
}
};
Given two integer arrays
Aand
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;
}
};
相关文章推荐
- [LeetCode] Maximum Length of Repeated Subarray 最长的重复子数组
- Leetcode | Maximum Length of Repeated Subarray
- Leetcode 718 Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray
- LeetCode-718:Maximum Length of Repeated Subarray (最长公共子数组) -- medium
- LeetCode:Maximum Length of Repeated Subarray
- 第16周Maximum Length of Repeated Subarray
- leetcode练习 Maximum Length of Repeated Subarray
- HashTable-718-Maximum Length of Repeated Subarray
- LeetCode #718 Maximum Length of Repeated Subarray
- 算法题目--Maximum Length of Repeated Subarray
- leetcode: Maximum Length of Repeated Subarray
- Array-Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray问题及解法
- LeetCode.718 Maximum Length of Repeated Subarray(经典DP问题)
- leetcode010-Maximum Length of Repeated Subarray(LCS动态规划)
- LeetCode:Maximum Length of Repeated Subarray
- arry-718 Maximum Length of Repeated Subarray
- Leetcode | Maximum Length of Repeated Subarray
- [leetcode]Maximum Length of Repeated Subarray