function strStr(haystack, needle) {
if (needle === '') return 0
// js已有轮子
// return haystack.indexOf(needle)
// 相当于自己实现一个indexOf方法
for (let i = 0; i < haystack.length; i++) {
if (haystack[i] === needle[0]) {
if (haystack.slice(i, i + needle.length) === needle) {
console.log(i)
return i
}
}
}
return -1
}
leetCode -实现一个strStr(),返回一个字符串在另一个字符串中出现的位置
本文介绍了一个用JavaScript实现的字符串查找函数,该函数不使用内置的indexOf方法,而是通过遍历目标字符串来查找指定子串的位置。文章提供了一个简单的示例代码,展示了如何逐字符比较并定位子串。

被折叠的 条评论
为什么被折叠?



