题目:
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
当 needle 是空字符串时我们应当返回 0 。
举例:
输入: haystack = “hello”, needle = “ll”
输出: 2
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
题干解析:
找haystack与needle的交集第一次出现的位置
借鉴别人的思路:判断 needle 是否在 haystack中
若在 则遍历haystack 利用字符串切片的方式判断是否等于needle
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
l1 = len(haystack)
l2 = len(needle)
if l2 == 0:
return 0
if needle in haystack:
for i in range(l1):
if haystack[i:i+l2] == needle:
return i
else:
return -1
我原先方法的别人实现:
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
i=0
j=0
if needle == "":
return 0
elif needle not in haystack:
return -1
if needle in haystack:
l1=len(haystack)
l2= len(needle)
while i<l1 and j<=l2: #利用while循环
if haystack[i] == needle[j]:
i+=1
j+=1
else:
i=i-j+1 #这个怎么来的 ????
#haystack="mississippi" needle='issip'
j=0
if j==l2:
return i-l2