美文网首页
28. Implement strStr()

28. Implement strStr()

作者: FlyCharles | 来源:发表于2019-03-06 11:47 被阅读0次

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()

      本文链接:https://www.haomeiwen.com/subject/bhczuqtx.html