Files
2020-08-09 00:39:24 +08:00

37 lines
2.5 KiB
Markdown
Executable File
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [718. Maximum Length of Repeated Subarray](https://leetcode.com/problems/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. 1 <= len(A), len(B) <= 1000
2. 0 <= A[i], B[i] < 100
## 题目大意
给两个整数数组 A B 返回两个数组中公共的长度最长的子数组的长度
## 解题思路
- 给出两个数组求这两个数组中最长相同子串的长度
- 这一题最容易想到的是 DP 动态规划的解法`dp[i][j]` 代表在 A 数组中以 `i` 下标开始的子串与 B 数组中以 `j` 下标开始的子串最长相同子串的长度状态转移方程为 `dp[i][j] = dp[i+1][j+1] + 1` ( `A[i] == B[j]`)。这种解法的时间复杂度是 O(n^2)空间复杂度 O(n^2)。
- 这一题最佳解法是二分搜索 + `Rabin-Karp`比较相同子串耗时的地方在于需要一层循环遍历子串所有字符但是如果比较两个数字就很快`O(1)` 的时间复杂度所以有人就想到了能不能把字符串也映射成数字呢这样比较起来就非常快这个算法就是 `Rabin-Karp` 算法字符串映射成一个数字不能随意映射还要求能根据字符串前缀动态增加比较下一个字符串的时候可以利用已比较过的前缀加速之后的字符串比较 Rabin-Karp 算法中有一个码点的概念类似于10进制中的进制具体的算法讲解可以见这篇
[基础知识 - Rabin-Karp 算法](https://www.cnblogs.com/golove/p/3234673.html)
码点一般取值为一个素数 go `strings` 包里面取值是 16777619所以这一题也可以直接取这个值由于这一次要求我们找最长长度所以把最长长度作为二分搜索的目标先将数组 A 和数组 B 中的数字都按照二分出来的长度进行 `Rabin-Karp` hash A 中的 hash 与下标做映射关系存到 map 方便后面快速查找然后遍历 B 中的 hash hash 一致的时候再匹配下标如果下标存在且拥有相同的前缀那么就算找到了相同的子串了最后就是不断的二分找到最长的结果即可这个解法的时间复杂度 O(n * log n)空间复杂度 O(n)。