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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值