给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,返回0
链接:https://leetcode-cn.com/problems/implement-strstr
python中内置方法:find()
下面两个代码思路一致,第二个更简洁。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle=='':
return 0
if needle not in haystack:
return -1
for i in range(len(haystack)):
if haystack[i] == needle[0]:
if haystack[i:i+len(needle)] == needle:
return i
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1