Code
/**
* @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;
};
Ideas
There is a concept sliding window.
That is, the entire needle is compared with the parts in the string. Swipe from left to right.
There will be 3 situations
- needle is empty
- needle length is longer than the original string
- Normal sliding-looking for the
first two are
emm strings that can be returned directly. Comparison is directly used === I believe it should be the fastest 23333