Implement strStr() Leetcode Solution Python

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Leetcode Solution (Python)

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(needle)
        #print(needle)
        
        for i in range(0,len(haystack)-n+1):
            substr = haystack[i:i+n]
            #print(substr)
            if substr == needle:
                return i
            
        return -1

Elements of Programming Interviews in Python: The Insiders’ Guide

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.