add: 最长重复子数组

This commit is contained in:
yi-ge 2020-07-01 18:10:39 +08:00
parent 3115552b87
commit 16ec46e003
3 changed files with 48 additions and 0 deletions

View File

@ -376,6 +376,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 739. 每日温度 <https://leetcode-cn.com/problems/daily-temperatures/> - LeetCode 739. 每日温度 <https://leetcode-cn.com/problems/daily-temperatures/>
- LintCode 1060. 每日温度 <https://www.lintcode.com/problem/daily-temperatures/description> - LintCode 1060. 每日温度 <https://www.lintcode.com/problem/daily-temperatures/description>
- [最长重复子数组](src/array/maximum-length-of-repeated-subarray.js)
- LeetCode 718. 最长重复子数组 <https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/>
- LintCode 79. 最长公共子串 <https://www.lintcode.com/problem/longest-common-substring/description>
## 栈 ## 栈
- [最大矩阵](src/stack/maximal-rectangle.js) - [最大矩阵](src/stack/maximal-rectangle.js)

View File

@ -0,0 +1,38 @@
// 输入:
// A: [1, 2, 3, 2, 1]
// B: [3, 2, 1, 4, 7]
const maxLength = function (A, B, addA, addB, len) {
addA = (addA > 0) ? addA : 0
addB = (addB > 0) ? addB : 0
let result = 0
let k = 0
for (let i = 0; i < len && (k + len - i > result); i++) {
if (A[i + addA] === B[i + addB]) {
k++
} else {
k = 0
}
result = Math.max(result, k)
}
return result
}
/**
* @param {number[]} A
* @param {number[]} B
* @return {number}
*/
export const findLength = function (A, B) {
const ALen = A.length
const BLen = B.length
let result = 0
for (let i = 1; i < ALen + BLen; i++) {
if (result >= (ALen + BLen - i)) {
return result
}
const len = Math.min(i, ALen, BLen, (ALen + BLen - i))
result = Math.max(maxLength(A, B, ALen - i, i - ALen, len), result)
}
return result
}

View File

@ -0,0 +1,5 @@
import { findLength } from '../../src/array/maximum-length-of-repeated-subarray.js'
test('最长重复子数组', () => {
expect(findLength([1, 2, 3, 2, 1], [3, 2, 1, 4, 7])).toBe(3)
})