题目:28实现 strStr()
代码:
var strStr = function(haystack, needle) {
const hLen = haystack.length
const nLen = needle.length
if (hLen < nLen) {
return -1
}
if (hLen === nLen) {
return haystack === needle ? 0 : -1
}
if (!hLen && nLen) {
return -1
}
if (!nLen) {
return 0
}
for (let i = 0; i < hLen - nLen + 1; i++) {
if (haystack.substr(i, nLen) === needle) {
return i
}
}
return -1
};