5/09/2020

[LeetCode] 28. Implement strStr()

Problem : https://leetcode.com/problems/implement-strstr/

This is a pretty naive approach.

Time Complexity :  O (len(haystack) * len(needle) )
Space Complexity:  O ( 1 )

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        
        if not needle:
            return 0
        
        for i in range(len(haystack) - len(needle) + 1):
            for j in range(len(needle)):
                if haystack[i+j] != needle[j]:
                    break
            else:
                # for-loop completed without break
                return i
        
        return -1

No comments:

Post a Comment