Leetcode - 28. Find the Index of the First Occurrence in a String

Javascript Code var strStr = function (haystack, needle) { if (needle.length === 0) return 0; if (needle.length > haystack.length) return -1; let n = needle.length; let h = haystack.length; for (let i = 0; i

Mar 1, 2025 - 09:57
 0
Leetcode - 28. Find the Index of the First Occurrence in a String

Javascript Code

var strStr = function (haystack, needle) {
    if (needle.length === 0) return 0;
    if (needle.length > haystack.length) return -1;

    let n = needle.length;
    let h = haystack.length;

    for (let i = 0; i <= h - n; i++) {
        let match = true;
        for (let j = 0; j < n; j++) {
            if (haystack[i + j] !== needle[j]) {
                match = false;
                break;
            }
        }
        if (match) return i;
    }

    return -1;
};