718.cc 991 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <vector>
  2. #include <cstring>
  3. #include <algorithm>
  4. using std::vector;
  5. using std::max;
  6. #define L 1000
  7. int dp[L + 1][L + 1];
  8. class Solution {
  9. public:
  10. int findLength(vector<int>& A, vector<int>& B) {
  11. // dp[i][j] means the max length of subarray end at A[i + 1] and B[j + 1]
  12. memset(dp, 0, sizeof(dp));
  13. int len = 0;
  14. for (int i = 1; i <= A.size(); i++) {
  15. for (int j = 1; j <= B.size(); j++) {
  16. if (A[i - 1] == B[j - 1]) {
  17. dp[i][j] = dp[i - 1][j - 1] + 1;
  18. len = max(len, dp[i][j]);
  19. }
  20. }
  21. }
  22. return len;
  23. }
  24. };
  25. #include <cstdio>
  26. int main() {
  27. Solution *sol = new Solution();
  28. vector<int> a = {1, 3, 1, 2, 1};
  29. vector<int> b = {3, 2, 1, 4, 7};
  30. int ans = sol->findLength(a, b);
  31. printf("%d\n", ans);
  32. a = {1, 2, 3, 2, 1};
  33. b = {3, 2, 1, 4, 7};
  34. ans = sol->findLength(a, b);
  35. printf("%d\n", ans);
  36. return 0;
  37. }