【python实现】 实现strStr()

实现 strStr() 函数。

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

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

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

思路:
遍历整个字符串,进行切片比较

解答:

class Solution:
    def strStr(self, haystack: 'str', needle: 'str') -> 'int':
        k = len(needle)
        if k == 0:
            return 0
        elif needle not in haystack:
            return -1
        else:
            for i in range(0, len(haystack)):
                if haystack[i] == needle[0]:
                    if haystack[i:i+k] == needle[:]:
                        return i

猜你喜欢

转载自blog.csdn.net/qq_41929011/article/details/87911977