DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

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;
};

Enter fullscreen mode Exit fullscreen mode

Efficient way of solving this is using Knuth–Morris–Pratt (KMP) Algorithm

Pending....

Top comments (0)