User Defined implementation for the required functionality.


  • 0
    R

    The idea here seems to have our own implementation of the function strStr so using the index function might not be the way to go.
    Here is my solution.

    class Solution:
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            if needle == haystack:
                return 0
            
            if len(needle)>len(haystack):
                return -1
            
            if len(needle)==0 and len(haystack)>0:
                return 0
            
            if len(needle) == 0:
                return -1
            
            for i in range(len(haystack)):
                if needle[0]==haystack[i]:
                    j,k=i,0
                    flag=0
                    while j<len(haystack) and k<len(needle) :
                        
                        if k<len(needle)-1 and j==len(haystack)-1:
                            return -1
                        
                        if needle[k] == haystack[j]:
                            flag=1
                        else:
                            flag=0
                            break
                        j+=1
                        k+=1
                    
                    if flag ==1:
                        start=i
                        return start
            
            return -1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.