current position:Home>Leetcode solution: 28. Implement strstr (), violence method, JavaScript, detailed notes

Leetcode solution: 28. Implement strstr (), violence method, JavaScript, detailed notes

2021-08-27 09:05:34 LeeChen

Original link :28. Realization strStr()

Their thinking :

  1. from i = 0 To i = haystack.length - needle.length Traverse haystack.
  2. from i Start , Judge one by one needle.length Characters of length , Whether each character is associated with needle The same characters as , If yes, it means that needle, return i.
/** * @param {string} haystack * @param {string} needle * @return {number} */
var strStr = function (haystack, needle) {
  //  Traverse haystack, And guarantee from i Begin to be able to find needle.length Length string 
  for (let i = 0; i <= haystack.length - needle.length; i++) {
    let judge = true //  Determine whether there is a connection with needle Equal string 

    //  from i Start , contrast needle.length Characters of length 
    for (let j = 0; j < needle.length; j++) {
      //  If there are unequal characters , There must be no equal to needle String , Exit loop 
      if (needle[j] !== haystack[i + j]) {
        //  take judge Set to false, Avoid misjudgment 
        judge = false
        break
      }
    }

    //  If the loop exits normally ,judge Keep for true, Said to find needle, Returns the index 
    if (judge) {
      return i
    }
  }

  //  Exit loop ,needle No , return -1
  return -1
}
 Copy code 
  1. Or you can use String.prototype.substr() Method , Intercept a string and compare .
/** * @param {string} haystack * @param {string} needle * @return {number} */
var strStr = function (haystack, needle) {
  //  Traverse haystack, And guarantee from i Begin to be able to find needle.length Length string 
  for (let i = 0; i <= haystack.length - needle.length; i++) {
    //  from haystack Medium intercept needle.length Long string 
    const sub = haystack.substr(i, needle.length)

    //  If sub And needle equal , Said to find needle, Returns the index 
    if (sub === needle) {
      return i
    }
  }

  //  Exit loop ,needle No , return -1
  return -1
}
 Copy code 

copyright notice
author[LeeChen],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827090531498h.html

Random recommended