|
38 | 38 |
|
39 | 39 | <!-- 这里可写通用的实现逻辑 -->
|
40 | 40 |
|
| 41 | +**方法一:动态规划** |
| 42 | + |
41 | 43 | <!-- tabs:start -->
|
42 | 44 |
|
43 | 45 | ### **Python3**
|
44 | 46 |
|
45 | 47 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
46 | 48 |
|
47 | 49 | ```python
|
48 |
| - |
| 50 | +class Solution: |
| 51 | + def findLength(self, nums1: List[int], nums2: List[int]) -> int: |
| 52 | + m, n = len(nums1), len(nums2) |
| 53 | + dp = [[0] * (n + 1) for _ in range(m + 1)] |
| 54 | + ans = 0 |
| 55 | + for i in range(1, m + 1): |
| 56 | + for j in range(1, n + 1): |
| 57 | + if nums1[i - 1] == nums2[j - 1]: |
| 58 | + dp[i][j] = 1 + dp[i - 1][j - 1] |
| 59 | + ans = max(ans, dp[i][j]) |
| 60 | + return ans |
49 | 61 | ```
|
50 | 62 |
|
51 | 63 | ### **Java**
|
52 | 64 |
|
53 | 65 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
54 | 66 |
|
55 | 67 | ```java
|
| 68 | +class Solution { |
| 69 | + public int findLength(int[] nums1, int[] nums2) { |
| 70 | + int m = nums1.length; |
| 71 | + int n = nums2.length; |
| 72 | + int[][] dp = new int[m + 1][n + 1]; |
| 73 | + int ans = 0; |
| 74 | + for (int i = 1; i <= m; ++i) { |
| 75 | + for (int j = 1; j <= n; ++j) { |
| 76 | + if (nums1[i - 1] == nums2[j - 1]) { |
| 77 | + dp[i][j] = dp[i - 1][j - 1] + 1; |
| 78 | + ans = Math.max(ans, dp[i][j]); |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + return ans; |
| 83 | + } |
| 84 | +} |
| 85 | +``` |
| 86 | + |
| 87 | +### **C++** |
| 88 | + |
| 89 | +```cpp |
| 90 | +class Solution { |
| 91 | +public: |
| 92 | + int findLength(vector<int>& nums1, vector<int>& nums2) { |
| 93 | + int m = nums1.size(), n = nums2.size(); |
| 94 | + vector<vector<int>> dp(m + 1, vector<int>(n + 1)); |
| 95 | + int ans = 0; |
| 96 | + for (int i = 1; i <= m; ++i) |
| 97 | + { |
| 98 | + for (int j = 1; j <= n; ++j) |
| 99 | + { |
| 100 | + if (nums1[i - 1] == nums2[j - 1]) |
| 101 | + { |
| 102 | + dp[i][j] = dp[i - 1][j - 1] + 1; |
| 103 | + ans = max(ans, dp[i][j]); |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + return ans; |
| 108 | + } |
| 109 | +}; |
| 110 | +``` |
56 | 111 |
|
| 112 | +### **Go** |
| 113 | +
|
| 114 | +```go |
| 115 | +func findLength(nums1 []int, nums2 []int) int { |
| 116 | + m, n := len(nums1), len(nums2) |
| 117 | + dp := make([][]int, m+1) |
| 118 | + for i := range dp { |
| 119 | + dp[i] = make([]int, n+1) |
| 120 | + } |
| 121 | + ans := 0 |
| 122 | + for i := 1; i <= m; i++ { |
| 123 | + for j := 1; j <= n; j++ { |
| 124 | + if nums1[i-1] == nums2[j-1] { |
| 125 | + dp[i][j] = dp[i-1][j-1] + 1 |
| 126 | + if ans < dp[i][j] { |
| 127 | + ans = dp[i][j] |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + return ans |
| 133 | +} |
57 | 134 | ```
|
58 | 135 |
|
59 | 136 | ### **...**
|
|
0 commit comments