1.先判断是否在内,再逐个搜索
class Solution: def strStr(self, haystack: str, needle: str) -> int: length = len(needle) if length == 0: return 0 if needle in haystack: if len(haystack)==1: return 0 for i in range(len(haystack)-length+1): # print(haystack[i:i+length]) if haystack[i:i+length] == needle: return i return -1
2.python自带api开挂
class Solution: def strStr(self, haystack: str, needle: str) -> int: return haystack.find(needle)