ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

力扣(leetcode)第28题找出字符串中第一个匹配项的下标(Python)

2026/8/15 13:35:52 拓冰建站 浏览量
力扣(leetcode)第28题找出字符串中第一个匹配项的下标(Python)

28.找出字符串中第一个匹配项的下标

题目链接:28.找出字符串中第一个匹配项的下标

给你两个字符串 h a y s t a c k haystack haystack n e e d l e needle needle ,请你在 h a y s t a c k haystack haystack 字符串中找出 n e e d l e needle needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 n e e d l e needle needle 不是 h a y s t a c k haystack haystack 的一部分,则返回 -1 。

示例 1:
输入:haystack = “sadbutsad”, needle = “sad”
输出:0
解释:“sad” 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。

示例 2:
输入:haystack = “leetcode”, needle = “leeto”
输出:-1
解释:“leeto” 没有在 “leetcode” 中出现,所以返回 -1 。

提示:

1 <= haystack.length, needle.length <= 104
h a y s t a c k haystack haystack n e e d l e needle needle 仅由小写英文字符组成

方法一

class Solution:def strStr(self, haystack: str, needle: str) -> int:i = 0size = len(needle)while i < len(haystack)-size+1:if haystack[i:i+size] == needle:return ielse:i+=1return -1

方法二


class Solution:def strStr(self, haystack: str, needle: str) -> int:try:return haystack.index(needle)except:return -1

最后,我写了一篇MySQL教程,里面详细的介绍了MySQL的基本概念以及操作指令等内容,欢迎阅读!
MySQL数据库万字保姆级教程