[leetcode] 718. Maximum Length of Repeated Subarray
Posted zmj97
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 718. Maximum Length of Repeated Subarray相关的知识,希望对你有一定的参考价值。
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
从A串的结尾开始向前遍历,记当前pos为i。
对每一个i,从B串的开始开始遍历,记当前pos为j,用dp[j]表示以i位置开头的A子串和以j位置开头的B子串最长重复串的长度。
则在对B遍历时,若当前pos为j,则当前的dp[j+1]是上一次的结果,即以i+1位置开头的A子串和以j+1位置开头的B子串最长重复串的长度; 这时,若A[i]与B[j]相等,则dp[j] = dp[j+1] + 1,否则为0。
上述也是表示了为什么要从B串的开头开始循环:为了在计算pos j 时, dp[j+1]记录的时pos i 的数据。也即若A[i]与B[j]相等, dp[i][j] = dp[i+1][j+1] + 1。
考虑到边界情况,dp数组申请长度为B长度+1。
我的代码:
class Solution { public: int findLength(vector<int>& A, vector<int>& B) { int len1= A.size(), len2 = B.size(); if (!len1 || !len2) return 0; vector<int> dp(len2+1); int re = 0; for (int i = len1 - 1; i >= 0; i--) { for (int j = 0; j < len2; j++) { dp[j] = (A[i] == B[j])?(1 + dp[j+1]):0; re = max(re, dp[j]); } } return re; } };
以上是关于[leetcode] 718. Maximum Length of Repeated Subarray的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode] 718. Maximum Length of Repeated Subarray
LeetCode-718. Maximum Length of Repeated Subarray
Leetcode 718. Maximum Length of Repeated Subarray
718. Maximum Length of Repeated Subarray