
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Implement strStr() in Python
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
- if str[i] = sub_str[j], then
- return -1
Let us see the implementation to get better understanding
Example (Python)
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
- Related Articles
- strstr() in C++
- strstr() function in PHP
- strstr() function in C/C++
- What is strstr() Function in C language?
- Implement IsNumber() function in Python
- Implement Trie (Prefix Tree) in Python
- Implement mean shift algorithm in Python
- Program to Implement Queue in Python
- How to Implement Priority Queue in Python?
- How to implement user defined exception in Python?
- How to implement immutable Data structures in Python?
- How to implement Concurrency with Threads in Python?
- Program to implement seat reservation manager in Python
- How do you implement persistent objects in Python?
- Python Program to Implement Shell Sort

Advertisements