Suppose we have two strings str and sub_str. We have to find the first occurrence of sub_str in the str. So if the string str is “helloworld”, and substring is “lo”, then the result will be 3.
This can be done using the strstr() function in C. We have to design another function that is similar to the strstr() in C.
To solve this, follow these steps −
Let us see the implementation to get better understanding
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ i = 0 j = 0 m = len(needle) n = len(haystack) if m ==0: return 0 while i<n and n-i+1>=m: if haystack[i] == needle[j]: temp = i while j<m and i<n and needle[j]==haystack[i]: i+=1 j+=1 if j == m: return temp i= temp+1 j = 0 else: i+=1 return -1 haystack = "helloworld" needle = "lo" ob1 = Solution() print(ob1.strStr(haystack, needle))
haystack = "helloworld" needle = "lo"