方案一:自己写的,很简单
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
l1 = len(needle)
l2 = len(haystack)
if l1==0:
return 0
for i in range(l2):
if haystack[i] == needle[0]:
if haystack[i:i+l1]==needle:
return i
return -1
方案二:
用自带的api str.find(),输入一个参数a,就可以在str中找到第一次出现该字符a的位置索引
def strStr(haystack: str, needle: str) -> int:
return haystack.find(needle)
print(strStr("hello","ll"))
print(strStr("hello","aab"))
print(strStr("hello",""))
leetcode 实现 strStr() python3
最新推荐文章于 2022-03-25 21:37:32 发布