題目
實現 strStr() 函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
-
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2 -
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
代碼
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return 0
if needle in haystack:
return len(haystack.split(needle)[0])
else:
return -1
本文鏈接:時光不寫博客-實現strStr()