Leetcode-28-实现strStr()

实现Python中find()功能,利用目标字符的长度分别截断已有字符串来查询

img

我的答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:

def strStr(self, haystack, needle):

"""

:type haystack: str

:type needle: str

:rtype: int

"""

len_needle = len(needle)

len_hay = len(haystack)


if not len_needle:

return 0

temp = [ haystack[i:i+len_needle] for i in range(len_hay - len_needle + 1)]

#print("temp:", temp)


for i in range(len(temp)):

if temp[i] == needle:

return i

else:

return -1

其实在python中已经有了相关的库,可以一句话就能实现此功能:a.find(b),但为了锻炼锻炼还是自己写一个

本题的主要思路是按照needle的长度,在heystack中截断对应长度的字符串放入临时对比列表中,如果在对比列表中存在needle,即存在,返回对比函数中的位置即为初始位置

needle,即存在,返回对比函数中的位置即为初始位置