Implement the strStr() function.
Given a haystack string and a needle string, find the first position (0-based) in the haystack string where the needle string occurs. Returns -1 if not present .
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
illustrate:
What value should we return when it needle
is an empty string? This is a good question to ask in an interview.
For this problem, needle
we should return 0 when it is an empty string. This matches the definition of strstr() in C and indexOf() in Java .
class Solution(object):
def strStr(self, haystack, needle):"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle)==0:
return 0
elif len(haystack)==0 or len(haystack) < len(needle):
return -1
m=len(haystack)
n=len(needle)
for i in range (0,m-n+1):
if needle[0]==haystack[i]:
j=1
while j<n:
print needle[j],haystack[j+i]
if needle[j]!=haystack[j+i]:
break
else :
j+=1
if j == n :
return i
return -1
Python can also be implemented directly with the following function
return haystack.find(needle)