Leetcode 28.实现 strStr()

题目:28.实现strStr() 讲解: https://www.bilibili.com/video/BV1PD4y1o7nd

初始思路

考点是KMP算法。

代码

  1. // 暴力算法
  2. var strStr = function (haystack, needle) {
  3. const needleLength = needle.length;
  4. const len = haystack.length
  5. // 当 needle 是空字符串时我们应当返回 0
  6. if (needleLength === 0) return 0;
  7. for (let i = 0; i < len; i++) {
  8. let j = 0;
  9. while (i + j < len && haystack[i + j] === needle[j]) {
  10. j++;
  11. }
  12. // 如果针对needle的指针到达了末尾,就认为匹配成功
  13. if (j === needleLength) {
  14. return i;
  15. }
  16. }
  17. // 如果不存在就返回-1
  18. return -1;
  19. };
  1. // KMP算法
  2. var strStr = function (haystack, needle) {
  3. const n = haystack.length, m = needle.length;
  4. const next = new Array(m).fill(0);
  5. // 计算前缀表
  6. for (let i = 1, j = 0; i < m; i++) {
  7. while (j > 0 && needle[i] !== needle[j]) {
  8. j = next[j - 1];
  9. }
  10. if (needle[i] === needle[j]) {
  11. j++;
  12. }
  13. next[i] = j;
  14. }
  15. // 根据前缀表进行匹配
  16. for (let i = 0, j = 0; i < n; i++) {
  17. while (j > 0 && haystack[i] !== needle[j]) {
  18. j = next[j - 1];
  19. }
  20. if (haystack[i] === needle[j]) {
  21. j++;
  22. }
  23. if (j === m) {
  24. return i - m + 1;
  25. }
  26. }
  27. return -1;
  28. };

感想

  1. 看得云里雾里,求前缀的部分没看懂。再多看看。。。