LeetCode_Implement strStr()

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. 遍历 – easy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
n = len(needle)
m = len(haystack)

if n == 0:
return 0

if n > m:
return -1

for i in range(m-n+1):
if haystack[i:i+n] == needle:
return i

return -1

2. 调用 python 库函数 in, index

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle not in haystack:
return -1
else:
return haystack.index(needle)