28. Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Solution: Two Pointers

class Solution(object):
    def strStr(self, source, target):
        """
        :type source: str
        :type target: str
        :rtype: int
        """
        i = 0
        j = 0
        while i < len(source) and j < len(target):
            if source[i] == target[j]:
                i += 1
                j += 1
            else:
                i -= j - 1
                j = 0
        return i - j if j == len(target) else -1

results matching ""

    No results matching ""