- Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
my thoughts:
1. check the first char then check the substring.
my solution:
**********32ms
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
i = 0
lh = len(haystack)
ln = len(needle)
while i + ln <= lh:
if haystack[i] != needle[0]:
i += 1
continue
elif haystack[i:i+ln] == needle:
return i
i += 1
return -1
my comments:
from other ppl's solution:
1. built-in func, find(), 25ms:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
2. substring in/not in string, 28ms:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle not in haystack:
return -1
return haystack.index(needle)