9-line Python solution, O(1) space, 60ms


  • 0
    K
    def strStr(self, haystack, needle):
        haystackPtr, haystackLen, needleLen = 0, len(haystack), len(needle)
        while True:
            needlePtr = 0
            while True:
                if needlePtr == needleLen: return haystackPtr
                if haystackPtr + needlePtr == haystackLen: return -1
                if needle[needlePtr] != haystack[haystackPtr + needlePtr]: break
                needlePtr += 1
            haystackPtr += 1

Log in to reply
 

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