leetcode 28. Implement strStr()
就是实现indexOf
var strStr = function (haystack, needle) {
if (!needle || haystack == needle) {//'' ,''或 'a' ,''
return 0
}
var n = haystack.length,
m = needle.length,
left = 0, right = 0;
if (n < m) {
return -1
}
while (left < n - m + 1) {
while (right < n && (right - left + 1 <= m)) {
if (haystack[left] !== needle[0]) {//加速
left++
right++
continue
}
if (right - left + 1 == m) {
var sub = haystack.substring(left, right + 1);
if (sub === needle) {
return left
}
}
right++
}
left++
}
return -1
};
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年