28. Implementing strStr()

Answer:

  1. fromi = 0toi = haystack.length - needle.lengthtraversehaystack.
  2. fromiStart by judging one by oneneedle.lengthLength of characters, whether each character is matched withneedleIs the same as the character, if yes, it means foundneedleTo return toi.
/ * * *@param {string} haystack
 * @param {string} needle
 * @return {number}* /
var strStr = function (haystack, needle) {
  // Iterate over haystack and make sure to find a needle. Length string starting from I
  for (let i = 0; i <= haystack.length - needle.length; i++) {
    let judge = true // Determine if there is a string equal to needle

    // Start with I and compare the needle. Length characters
    for (let j = 0; j < needle.length; j++) {
      If there are unequal characters, there must be no string equal to needle, exit the loop
      if(needle[j] ! == haystack[i + j]) {// Set judge to false to avoid false judgments
        judge = false
        break}}// If it exits the loop normally, judge stays true, indicating that needle is found and the index is returned
    if (judge) {
      return i
    }
  }

  // Exit loop, needle does not appear, return -1
  return -1
}
Copy the code
  1. Or you can useString.prototype.substr()Method to capture a string for comparison.
/ * * *@param {string} haystack
 * @param {string} needle
 * @return {number}* /
var strStr = function (haystack, needle) {
  // Iterate over haystack and make sure to find a needle. Length string starting from I
  for (let i = 0; i <= haystack.length - needle.length; i++) {
    // Select a needle. Length string from haystack
    const sub = haystack.substr(i, needle.length)

    // If sub is equal to needle, needle is found
    if (sub === needle) {
      return i
    }
  }

  // Exit loop, needle does not appear, return -1
  return -1
}
Copy the code