Title description:
Implement the strStr() function.
Given a haystack string and a needle string, find the first position (starting from 0) of the needle string in the haystack string. Returns -1 if not present.
Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Explanation:
illustrate:
What should we return when needle is an empty string? This is a great question to ask in an interview.
For this question, we should return 0 when needle is an empty string. This matches the definition of strstr() in C and indexOf() in Java.
Problem-solving ideas:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
haystack_len = len(haystack)
for idx in range(haystack_len):
needle_len = len(needle)
cnt = 0
if idx + needle_len > haystack_len:
break
for jdx in range(needle_len):
if haystack[idx + jdx] == needle[jdx]:
cnt = cnt + 1
else:
break
if cnt == needle_len:
return idx
return -1
Algorithm performance: