本文主要是介绍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].
思路:跟Longest Common Substring && Longest continuous Common History 很类似;
dp[i][j] = dp[i - 1][j - 1] + 1; s[i] == s[j]
class Solution {public int findLength(int[] A, int[] B) {if(A == null || B == null) {return 0;}int n = A.length;int m = B.length;int maxlen = 0;int[][] dp = new int[n + 1][m + 1];for(int i = 1; i <= n; i++) {for(int j = 1; j <= m; j++) {if(A[i - 1] == B[j - 1]) {dp[i][j] = dp[i - 1][j - 1] + 1;maxlen = Math.max(maxlen, dp[i][j]);} else {dp[i][j] = 0;}}}return maxlen;}
}
这篇关于Maximum Length of Repeated Subarray的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!