[勇者闯LeetCode] 28. Implement strStr()
Description
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Information
- Tags: Two Pointers | String
- Difficulty: Easy
Solution
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return 0
lh, ln = len(haystack), len(needle)
if lh < ln:
return -1
elif lh == ln:
return 0 if haystack == needle else -1
else:
for i in range(lh-ln+1):
if haystack[i:i+ln] == needle:
return i
return -1