28. Implement strStr()

1. 我的AC

方法一

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

方法二

  • 讨论区高票版本
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

你可能感兴趣的:(28. Implement strStr())