28. Find the Index of the First Occurrence in a String
¶
- Time: $O((m - n)n)$, where $m = |\texttt{haystack}|$ and $n = |\texttt{needle}|$
- Space: $O(1)$
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 | |
var strStr = function(haystack, needle) {
if (!needle) return 0;
for (let i = 0; i + needle.length <= haystack.length; i++) {
if (haystack.slice(i, i + needle.length) === needle) return i;
}
return -1;
};