Implement strStr()
Problem
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1
if needle
is not part of haystack
.
Solution
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
length = len(needle)
if needle == "":
return 0
for i in range(len(haystack)):
if haystack[i:i+length] == needle:
return i
return -1
#Time: O(n)
#Space: O(1)
#Its just substring matching
Last updated
Was this helpful?