Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Implement strStr() in Python
The strStr() function finds the first occurrence of a substring within a string and returns its index. This is similar to the strstr() function in C programming. If the substring is not found, it returns -1.
Algorithm
To implement strStr(), we use a two-pointer approach with the following steps ?
- Initialize i = 0 (for main string), j = 0 (for substring)
- If substring is empty, return 0
- While i = substring length:
- If characters match, compare the entire substring
- If complete match found, return starting index
- Otherwise, move to next position in main string
- If no match found, return -1
Implementation
class Solution:
def strStr(self, haystack, needle):
"""
Find the first occurrence of needle in haystack
:param haystack: Main string to search in
:param needle: Substring to find
:return: Index of first occurrence or -1 if not found
"""
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
# Test the implementation
haystack = "helloworld"
needle = "lo"
solution = Solution()
result = solution.strStr(haystack, needle)
print(f"Index of '{needle}' in '{haystack}': {result}")
Index of 'lo' in 'helloworld': 3
Using Built-in Method
Python provides a simpler approach using the find() method ?
def strStr_builtin(haystack, needle):
if not needle:
return 0
return haystack.find(needle)
# Test with different examples
test_cases = [
("helloworld", "lo"),
("programming", "gram"),
("python", "java"),
("", ""),
("abc", "")
]
for haystack, needle in test_cases:
result = strStr_builtin(haystack, needle)
print(f"'{needle}' in '{haystack}': {result}")
'lo' in 'helloworld': 3 'gram' in 'programming': 3 'java' in 'python': -1 '' in '': 0 '' in 'abc': 0
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Manual Implementation | O(n*m) | O(1) | Understanding algorithm |
| Built-in find() | O(n*m) worst case | O(1) | Production code |
Conclusion
The strStr() function can be implemented using a two-pointer approach to find substring occurrences. For practical applications, Python's built-in find() method provides the same functionality with cleaner syntax.
Advertisements
