leetcode28: implement strstr() 2. Analysis 3. Solution(s)

Link

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

2. Analysis

3. Solution(s)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class (object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return 0
i = 0
while i <= len(haystack)-len(needle):
if haystack[i] == needle[0]:
j = 0
while j < len(needle):
if needle[j] != haystack[i+j]:
break
else:
j += 1
if j == len(needle):
return i
i += 1
return -1