image.png

题解

1. 动态规划

通过一个二维数组arr[i][j]表示第一个字符串前i个字符和第二个字符串前j个字符组成的最长公共字符串的长度。
image.png

代码

  1. function findLength(A: number[], B: number[]): number {
  2. // 基础版本
  3. // let ALen = A.length;
  4. // let BLen = B.length;
  5. // let arr = new Array(ALen + 1).fill(0).map(()=>new Array(BLen + 1).fill(0));
  6. // let max = 0;
  7. // for (let i = 1; i <= ALen; i++) {
  8. // for (let j = 1; j <= BLen; j--) {
  9. // if (A[i - 1] === B[j - 1]) {
  10. // arr[i][j] = arr[i-1][j - 1] + 1;
  11. // } else {
  12. // arr[i][j] = 0;
  13. // }
  14. // max = Math.max(max, arr[i][j]);
  15. // }
  16. // }
  17. // return max;
  18. // 优化版
  19. let ALen = A.length;
  20. let BLen = B.length;
  21. let arr = new Array(BLen + 1).fill(0)
  22. let max = 0;
  23. for (let i = 1; i <= ALen; i++) {
  24. for (let j = B.length; j > 0; j--) {
  25. if (A[i - 1] === B[j - 1]) {
  26. arr[j] = arr[j - 1] + 1;
  27. } else {
  28. arr[j] = 0;
  29. }
  30. max = Math.max(max, arr[j]);
  31. }
  32. }
  33. return max;
  34. };

image.png

2. 滑动窗口

image.png

代码

  1. // 计算红框的最大长度
  2. function maxLen(M: number[], N: number[], i: number, j: number, len: number): number {
  3. console.log(M.slice(i),N.slice(j);
  4. let res: number = 0;
  5. let count: number = 0;
  6. for (let k = 0; k < len; k++) {
  7. if (M[i + k] === N[j + k]) {
  8. count++;
  9. } else {
  10. count = 0;
  11. }
  12. res = Math.max(res, count);
  13. }
  14. return res;
  15. }
  16. // 主函数
  17. function findLength(A: number[], B: number[]): number {
  18. let a = A.length;
  19. let b = B.length;
  20. let ret = 0;
  21. for (let i = 0; i < a; i++) {
  22. let len = Math.min(b, a - i);
  23. let max = maxLen(A, B, i, 0, len);
  24. ret = Math.max(ret, max);
  25. }
  26. for (let i = 0; i < b; i++) {
  27. let len = Math.min(a, b - i);
  28. let max = maxLen(A, B, 0, i, len);
  29. ret = Math.max(ret, max);
  30. }
  31. return ret;
  32. };

上图中console如下
image.png

image.png