【第十四周】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、动态规划
阅读全文
0 0
- 【第十四周】718. Maximum Length of Repeated Subarray
- Leetcode 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718.Maximum Length of Repeated Subarray(M)
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 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
- [LeetCode]718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- python操作excel之写入数据(1)——xlwt
- android_activity生命周期
- 2017年12月20日的总作总结
- android java使用proto-2.6.1-win32
- 解决python初学问题TemplatesDoesNotExist
- 【第十四周】718. Maximum Length of Repeated Subarray
- python核心编程第二版第二章学习笔记
- jquery中attr和prop的区别
- 三十五、面向对象相关扩展
- 前端代码套上安卓壳子
- 大东哥博客
- BZOJ4566:[HAOI2016]找相同字符(广义SAM)
- 五三、提取浏览器 url 中的参数名和参数值,生成一个key/value 的对象
- java编码