28. Implement strStr()

Posted Premiumlab

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了28. Implement strStr()相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/implement-strstr/#/description

 

Implement strStr().

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

 

Sol:

 

Needle is a short block string while haystack is a long block string. Move the short block to check if it is in the long block.

 

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        for i in range(len(haystack) - len(needle) + 1):
            if haystack[i:i + len(needle)] == needle:
                return i 
        return -1

 

 

Other solutions may use KMP algorithm...

以上是关于28. Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 28. Implement strStr() 实现strStr()

28. Implement strStr()

28. Implement strStr()

[LeetCode] 28. Implement strStr() 实现strStr()函数

28. Implement strStr()

28. Implement strStr()(js)