LeetCode第28题:实现strStr()

版权声明:欢迎转载,转载请注明出处 https://blog.csdn.net/weixin_44649870/article/details/87923033

LeetCode第28题:实现strStr()

题目

实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

  • 示例 1:
    输入: haystack = “hello”, needle = “ll”
    输出: 2
  • 示例 2:
    输入: haystack = “aaaaa”, needle = “bba”
    输出: -1

代码

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle == "":
            return 0
        if needle in haystack:
            return len(haystack.split(needle)[0])
        else:
            return -1
        

猜你喜欢

转载自blog.csdn.net/weixin_44649870/article/details/87923033
今日推荐