Leetcode problem solution-implement strStr()

Code

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    
    
    if (needle === '') return 0;
    let l = haystack.length;
    let n = needle.length;
    for (let i = 0; i < l - n + 1; i++) {
    
    
      if (haystack.substring(i, i + n) === needle) {
    
    
        return i;
      }
    }
    return -1;
};

Ideas

There is a concept sliding window.
That is, the entire needle is compared with the parts in the string. Swipe from left to right.
There will be 3 situations

  1. needle is empty
  2. needle length is longer than the original string
  3. Normal sliding-looking for the
    first two are
    emm strings that can be returned directly. Comparison is directly used === I believe it should be the fastest 23333

Guess you like

Origin blog.csdn.net/weixin_38616850/article/details/106892041