leetcode-28-实现 strStr()

实现 strStr() 函数。

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

解决方法:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        L, N = len(haystack), len(needle)
        for i in range(L-N+1):
            # 将needle整个去和haystack进行匹配
            if haystack[i:len(needle)+i] == needle:
                return i
        return -1

猜你喜欢

转载自blog.csdn.net/xinxiang7/article/details/106367612