代码
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if (needle === '') return 0;
let l = haystack.length;
let n = needle.length;
for (let i = 0; i < l - n + 1; i++) {
if (haystack.substring(i, i + n) === needle) {
return i;
}
}
return -1;
};
思路
有一个概念 滑动窗口 。
即用整个needle 与 字符串中的部分 进行比较。从左到右滑动。
会出现3种情况
- needle是空
- needle长度比原字符串还长
- 正常滑动 - 寻找
前两种都是可以直接返回的
emm 字符串比较直接用了 === 相信应该是最快的了 23333