Ruby's Louvre

每天学习一点点算法

导航

leetcode 28. Implement strStr()

就是实现indexOf


var strStr = function (haystack, needle) {
      if (!needle || haystack == needle) {//'' ,''或 'a' ,''
        return 0
      }
      var n = haystack.length,
        m = needle.length,
        left = 0, right = 0;
      if (n < m) {
        return -1
      }

      while (left < n - m + 1) {
        while (right < n && (right - left + 1 <= m)) {
          if (haystack[left] !== needle[0]) {//加速
            left++
            right++
            continue
          }
          if (right - left + 1 == m) {
            var sub = haystack.substring(left, right + 1);
            if (sub === needle) {
              return left
            }
          }
          right++
        }
        left++
      }
      return -1
    };

posted on 2019-12-15 12:45  司徒正美  阅读(173)  评论(0编辑  收藏  举报