ac solution code


  • 0

    The basic idea is to use two pointers(i, j) to check whether needle occurs in haystack as requirement.

        /*
         Solution1. Two Pointers: time = O(nm); space = O(1)
         */
           func strStr(_ haystack: String, _ needle: String) -> Int {
            let hChars = Array(haystack.characters), nChars = Array(needle.characters)
            let hLen = hChars.count, nLen = nChars.count
            guard hLen >= nLen else {
                return -1
            }
            guard nLen != 0 else {//empty need matchs any haystack at index 0
                return 0
            }
            for i in 0 ... hLen - nLen {
                for j in 0 ..< nLen {
                    if hChars[i + j] != nChars[j] {
                        break
                    }
                    if j == nLen - 1 {// reach the end of needle with all characters match in haystack
                        return i
                    }
                }
            }
            return -1
        }
    

Log in to reply
 

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