★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-kdautdie-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given two integer arrays A
and B
, return the maximum length of an subarray that appears in both arrays.git
Example 1:github
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:數組
給兩個整數數組 A
和 B
,返回兩個數組中公共的、長度最長的子數組的長度。微信
示例 1:app
輸入: A: [1,2,3,2,1] B: [3,2,1,4,7] 輸出: 3 解釋: 長度最長的公共子數組是 [3, 2, 1]。
說明:spa
308mscode
1 class Solution { 2 func findLength(_ A: [Int], _ B: [Int]) -> Int { 3 var ret = 0 4 let lenA = A.count, lenB = B.count 5 for k in 1..<(lenA + lenB) { 6 var i = max(0, lenA - k) 7 var j = max(0, k - lenA) 8 var len = 0 9 while i < lenA && j < lenB { 10 len = (A[i] == B[j]) ? (len + 1) : 0 11 ret = max(ret, len) 12 i += 1 13 j += 1 14 } 15 } 16 return ret 17 } 18 }
1304mshtm
1 class Solution { 2 func findLength(_ A: [Int], _ B: [Int]) -> Int { 3 let m = A.count, n = B.count 4 var res = 0 5 6 var dp = [[Int]](repeating:[Int](repeating: 0, count: n+1), count: m + 1) 7 8 for i in 1...m { 9 for j in 1...n { 10 if A[i-1] == B[j-1] { 11 dp[i][j] = 1 + dp[i-1][j-1] 12 res = max(res, dp[i][j]) 13 } 14 } 15 } 16 return res 17 } 18 }
1 class Solution { 2 func findLength(_ A: [Int], _ B: [Int]) -> Int { 3 var res:Int = 0 4 var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:B.count + 1),count:A.count + 1) 5 for i in 1..<dp.count 6 { 7 for j in 1..<dp[i].count 8 { 9 dp[i][j] = (A[i - 1] == B[j - 1]) ? dp[i - 1][j - 1] + 1 : 0 10 res = max(res, dp[i][j]) 11 } 12 } 13 return res 14 } 15 }