Skip to main content

28. Find the Index of the First Occurrence in a String

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string

Python

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n, m = len(haystack), len(needle)
if n < m:
return -1
if n == m:
return 0 if haystack == needle else -1

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