问题 - 给定两个字符串
needle
和 haystack
,返回 needle
中第一次出现 haystack
的索引,如果 -1
不是 needle
的一部分,则返回 haystack
。 (问题来自Leetcode)
示例 - 输入:haystack = "sadbutsad", needle = "sad"
输出:0
和
输入:haystack = "leetcode", needle = "leeto"
输出:-1
我的代码
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle not in haystack:
return -1
else:
for i in range (0, (len(haystack)-len(needle))+1):
if haystack[i:i+len(needle)] == needle:
return i
break
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)