题目描述
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
当 needle 是空字符串时返回 0 。
示例
输入: haystack = “hello”, needle = “ll”
输出: 2
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
解答
遍历haystack字符串,判断其与needle字符串等长的片段是否与needle字符串相同
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len_need = len(needle)
if len_need==0:
return 0
end = len(haystack) - len_need
for i in range(0,end+1):
if haystack[i:i+len_need] == needle:
return i
return -1