We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
原题链接:28. 实现 strStr()
解题思路:
i = 0
i = haystack.length - needle.length
haystack
i
needle.length
needle
/** * @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 }
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 }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接:28. 实现 strStr()
解题思路:
i = 0
到i = haystack.length - needle.length
遍历haystack
。i
开始,逐个判断needle.length
长度的字符,是否每个字符都与needle
的字符相同,如果是则表示找到needle
,返回i
。String.prototype.substr()
方法,截取一段字符串对比。The text was updated successfully, but these errors were encountered: