leetcode-python-实现strStr()

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)

 

posted @ 2021-05-31 15:53  泊鸽  阅读(74)  评论(0)    收藏  举报