leetcode-easy-string-28 Implement strStr()

mycode   77.15%

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

参考:

要习惯python的.find操作呀

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):
        if not needle:
            return 0
        return haystack.find(needle)
原文地址:https://www.cnblogs.com/rosyYY/p/10996320.html