如何减少这个问题中代码的运行时间

问题描述 投票:0回答:1

问题 - 给定两个字符串

needle
haystack
,返回
needle
中第一次出现
haystack
的索引,如果
-1
不是
needle
的一部分,则返回
haystack
。 (问题来自Leetcode) 示例 - 输入:
haystack = "sadbutsad", needle = "sad"
输出:
0
和 输入:
haystack = "leetcode", needle = "leeto"
输出:
-1

我的代码

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle not in haystack:
            return -1 
        else:
            for i in range (0, (len(haystack)-len(needle))+1):
                if haystack[i:i+len(needle)] == needle:
                    return i
                    break

python performance big-o
1个回答
0
投票
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)
© www.soinside.com 2019 - 2024. All rights reserved.