Implement strStr() in Python

PythonServer Side ProgrammingProgramming

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 −

  • i := 0, j := 0, m := length of sub_str and n := length of str
  • if m = 0, then return 0
  • while i < n and n – i + 1 = m, do
    • if str[i] = sub_str[j], then
      • temp := j
      • while j < m and i < n and sub_str[j] == str[j], do
        • increase i and j by 1
      • if j = m, then return temp
      • i := temp + 1
      • j := 0
    • else increase i by 1
  • return -1

Let us see the implementation to get better understanding

Example (Python)

 Live Demo

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))

Input

haystack = "helloworld"
needle = "lo"

Output

3
raja
Published on 08-Jan-2020 10:42:57
Advertisements