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)

 

上一篇:791. Custom Sort String


下一篇:吴恩达机器学习作业8(下)--- 推荐系统