Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:28. 实现 strStr(),暴力法,JavaScript,详细注释 #370

Open
chencl1986 opened this issue Aug 23, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:28. 实现 strStr()

解题思路:

  1. i = 0i = haystack.length - needle.length遍历haystack
  2. i开始,逐个判断needle.length长度的字符,是否每个字符都与needle的字符相同,如果是则表示找到needle,返回i
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
  // 遍历haystack,并保证从i开始能够查找到needle.length长度的字符串
  for (let i = 0; i <= haystack.length - needle.length; i++) {
    let judge = true // 判断是否存在与needle相等的字符串

    // 从i开始,对比needle.length长度的字符
    for (let j = 0; j < needle.length; j++) {
      // 如果有不相等的字符,必然不存在等于needle的字符串,退出循环
      if (needle[j] !== haystack[i + j]) {
        // 将judge设置为false,避免错误判断
        judge = false
        break
      }
    }

    // 如果正常退出循环,judge保持为true,表示找到needle,返回索引
    if (judge) {
      return i
    }
  }

  // 退出循环,needle未出现,返回-1
  return -1
}
  1. 或者可以使用String.prototype.substr()方法,截取一段字符串对比。
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
  // 遍历haystack,并保证从i开始能够查找到needle.length长度的字符串
  for (let i = 0; i <= haystack.length - needle.length; i++) {
    // 从haystack中截取needle.length长的字符串
    const sub = haystack.substr(i, needle.length)

    // 如果sub与needle相等,表示找到needle,返回索引
    if (sub === needle) {
      return i
    }
  }

  // 退出循环,needle未出现,返回-1
  return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant