leetcode--28. 實現strStr()

題目:28. 實現strStr()

鏈接:https://leetcode-cn.com/problems/implement-strstr/description/

在字符串haystack中尋找子串needle第一次出現的位置,若匹配失敗返回-1。

其實就是python字符串的find方法。下面是一個KMP算法:

python:

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        def getNext(str):
            length = len(str)
            next = [-1 for i in range(length + 1)]
            j, k = 0, -1
            while j < length:
                if k == -1 or str[j] == str[k]:
                    j, k = j + 1, k + 1
                    next[j] = k
                else:
                    k = next[k]
            return next

        def KMP(s, p):
            next = getNext(p)
            j = k = 0
            length = len(s)
            while j < length:
                if s[j] == p[k] or k == -1:
                    j += 1
                    k += 1
                else:
                    k = next[k]
                if k == len(p):
                    return j - k
            return -1
        return KMP(haystack,needle)
        # return (haystack.find(needle))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章