Swift naive solution


  • 0
    N

    I haven't found a swift solution so I update this one. Can you guys help me improve this? I have tried other algorithm but all of them are over the time limit except this naive method.

    class Solution {
        func strStr(haystack: String, _ needle: String) -> Int {
            
            var haystackTemp = haystack
            
            let haystackLen = haystack.characters.count
            let needleLen = needle.characters.count
            
            // error checking
            if !haystack.isEmpty && needle.isEmpty {
                return 0
            }
            if haystack.isEmpty && !needle.isEmpty {
                return -1
            }
            
            if haystackLen == needleLen {
                if haystack == needle {
                    return 0
                } else {
                    return -1
                }
            } else if haystackLen < needleLen {
                return -1
            }
            
            var index: Int
    
            
            for index = 0; index < haystackLen - needleLen + 1; index++ {
                if haystackTemp.hasPrefix(needle) {
                    return index
                } else {
                    haystackTemp = haystackTemp.substringFromIndex(haystackTemp.startIndex.successor())
                }
            }
            return -1
        }
    }

Log in to reply
 

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