Question:

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example:

  1. Input: haystack = "hello", needle = "ll"
  2. Output: 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1

Solution:

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

Runtime: 76 ms, faster than 15.02% of JavaScript online submissions for Implement strStr().