python LeetCode 刷题记录 28

题目

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。

代码

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not haystack or not needle:
            return 0
        for i, ss in enumerate(haystack):
            if i > len(haystack) - len(needle):
                return -1
            elif ss == needle[:1] and haystack[i:len(needle) + i] == needle:
                return i
        return -1

你可能感兴趣的:(LeetCode,python,leetcode)