Python, LeetCode, 28. 实现strStr()

#KMP
class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle) == 0:
            return 0
        if len(haystack) == 0:
            return -1
        M = len(haystack)
        N = len(needle)
        ptr_s = 0
        ptr_t = 0
        next_pos = self.getNext_pos(needle)
        while ptr_s < M and ptr_t < N:
            if ptr_t == -1 or haystack[ptr_s] == needle[ptr_t]:
                ptr_s += 1
                ptr_t += 1
            else:
                ptr_t = next_pos[ptr_t]       
        if ptr_t == N:
            return ptr_s - N
        else:
            return -1
    
    def getNext_pos(self, needle):
        next_pos = [-1] * len(needle)
        i = 0
        j = -1
        while i < len(needle) - 1:
            if j == -1 or needle[i] == needle[j]:
                i += 1
                j += 1
                next_pos[i] = j
            else:
                j = next_pos[j]
        return next_pos

#Sunday
class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle) == 0:
            return 0
        if len(haystack) == 0:
            return -1
        M = len(haystack)
        N = len(needle)
        if N > M:
            return -1
        elif N == M:
            tmp = N - 1
        else:
            tmp = N
        ptr_h = 0
        ptr_n = 0
        
        while tmp < M:
            while ptr_h < M and ptr_n < N and haystack[ptr_h] == needle[ptr_n]:
                ptr_h += 1
                ptr_n += 1
            if ptr_n == N:
                return ptr_h - N
            elif haystack[tmp] in needle:
                ptr_n = N - 1
                while ptr_n >= 0:
                    if haystack[tmp] == needle[ptr_n]:
                        if tmp - ptr_n + N > M:
                            return -1
                        for x in range(N):
                            if haystack[tmp - ptr_n + x] != needle[x]:
                                ptr_n -= 1
                                break
                            elif x == N-1:
                                return tmp - ptr_n
                    else:
                        ptr_n -= 1
                tmp += N
                ptr_h += N
                ptr_n = 0
            else:
                tmp += N + 1
                ptr_h += N + 1
                ptr_n = 0
        return -1

你可能感兴趣的:(LeetCode)