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:
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
code:class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
index = 0
ln = len(needle)
if ln == 0:
return 0
for s in haystack:
if index+ln > len(haystack):
return (-1)
if haystack[index:index+ln] == needle:
return (index)
else:
index += 1
return -1
笔记:代码中 haystack[index:index+ln],截取原字符中的某一段来比较。