代码:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

最快版本,使用方法:

使用Index()字符串方法,如果匹配到了子串,返回索引。也可以使用find()字符串方法,俩者在成功查找后均可以返回索引,但是index()在查找失败以后是抛出异常,而find()查找失败以后是返回-1

https://blog.csdn.net/ztf312/article/details/47657963

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        
        if needle in haystack:
            return haystack.index(needle)
        return -1

 

我的版本,不使用库直接用逻辑处理。很c++nic,,,

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        hs=len(haystack)
        ne=len(needle)
        for i in range(hs-ne+1):
            j,k=0,i
            while haystack[k]==needle[j]:
                if j==ne-1:
                    return i
                k,j=k+1,j+1
        return -1
                
        
        
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄