【第十四周】718. Maximum Length of Repeated Subarray

来源:互联网 发布:淘宝卖家改价要收费吗 编辑:程序博客网 时间:2024/06/04 18:49

原题

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: 3Explanation: The repeated subarray with maximum length is [3, 2, 1].Note:1 <= len(A), len(B) <= 10000 <= A[i], B[i] < 100

leetCode地址:https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/

解题思路

题目大意:
给出两个数串A和B,求A与B的最长重复子串的长度。

这是一个经典的动态规划模型。定义状态F(j,k)表示 以A[j]和B[k]结尾数串的最长重复子串长度;状态转移方程为F(j+1, k+1) = A[j+1] == B[k+1] ?F[j,k] +1 : 0。有了状态和状态转移的定义,就可以很容易写出动态规划的算法了。

代码

class Solution {public:    int findLength(vector<int>& A, vector<int>& B) {        int m = A.size(), n = B.size();        if (m == 0 || n == 0) return 0;           int dp[1000][1000];        int ret = 0;        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (i == 0 || j == 0) {                    dp[i][j] = A[i] == B[j] ? 1 : 0;                } else {                    dp[i][j] = (A[i] == B[j] ? dp[i-1][j-1] + 1 : 0);                }                if (ret < dp[i][j]) ret = dp[i][j];            }        }        return ret;    }};

总结

1、动态规划

原创粉丝点击