找出字符串中第一个匹配项的下标
https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/
给你两个字符串haystack和needle,请你在haystack字符串中找出needle字符串的第一个匹配项的下标(下标从0开始)。如果needle不是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 <= 10^4
- haystack和needle仅由小写英文字符组成
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(0, len(haystack)):
if haystack[i:].startswith(needle):
return i
return -1