就是实现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
};