Swift solution - Two Pointers


  • 0
    class Solution {
        func strStr(_ haystack: String, _ needle: String) -> Int {
            if needle.characters.count == 0 {
                return 0
            }
            if needle.characters.count > haystack.characters.count {
                return -1
            }
            
            let haystackChars = Array(haystack.characters)
            let needleChars = Array(needle.characters)
            var i = 0
            var j = 0
            
            while i < haystackChars.count {
                if haystackChars[i] == needleChars[j] {
                    j += 1
                    if j == needleChars.count {
                        return i - j + 1
                    }
                } else {
                    i -= j
                    j = 0
                }
                i += 1
            }
            
            return -1
        }
    }
    

Log in to reply
 

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