DEV Community

Cover image for Practice LeetCode Problem - Implement strStr()

Practice LeetCode Problem - Implement strStr()

Kristen Kinnear-Ohlmann on May 09, 2022

I have been diligently working on data structure and algorithm problems from various sources. Today I worked on the Implement strStr() problem usin...
Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

I don't know if it's a good idea to solve this using existing string and array functions?

   var strStr = function( haystack, needle ) {
    let [i,ni,compare] = [-1,-1,true]
    while(haystack[++i]){
        while ((needle[++ni] != undefined) && compare)
          compare = haystack[i+ni] == needle[ni]
        if (compare) return i 
        ni = -1
        compare = true
    }
    return !needle ? 0 : -1
  }
Enter fullscreen mode Exit fullscreen mode