Golang simple brute-force solution


  • 0

    Do we need to solve this using KMP or BM in an interview...?

    func strStr(haystack string, needle string) int {
        if len(needle) == 0 {
            return 0
        }
        
        i := 0
        for i < len(haystack) {
            if haystack[i] == needle[0] {
                j := 1
                for ; j < len(needle); j++ {
                    if i + j >= len(haystack) || haystack[i+j] != needle[j] {
                        break
                    }
                }
                
                if j == len(needle) {
                    return i    
                }
            }
            i++
        }
        return -1
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.