28. Implement strStr()

Implement strStr().

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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

 

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

 

以上

posted on 2018-08-30 11:08  jydd  阅读(52)  评论(0编辑  收藏  举报

导航