LeetCode Easy: 28. Implement strStr()
一、题目
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
二、思路
首先我想到的就是python中特有的切片功能,遍历给定的 haystack ,然后与needle进行匹配,考虑鲁棒性当needle长度小于haystack的长度,返回-1.
三、代码
#coding:utf-8
def strStr(haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle)>len(haystack):
return -1
else:
for i in range((len(haystack)-len(needle)+1)):
if needle == haystack[i:i+len(needle):1]:
print(i)
return i
return -1
if __name__ == '__main__':
a = "hello"
b = 'dl'
strStr(a,b)
niasd
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号