Swift Solution


  • 0
    J
    let haystackLength = haystack.count
        let needleLength = needle.count
        if needleLength > haystackLength {
            return -1
        }
        for i in 0 ..< haystackLength - needleLength + 1 {
            let startIndex = haystack.index(haystack.startIndex, offsetBy: i)
            let endIndex = haystack.index(haystack.startIndex, offsetBy: i + needleLength)
            if haystack[startIndex..<endIndex] == needle {
                return i
            }
        }
        return -1
    

Log in to reply
 

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