python - 如何解决leetcode中超过时间限制的错误

标签 python python-3.x performance

我已经在 LeetCode 中编写了最长公共(public)前缀的代码,但返回“超出时间限制”。

没有具体的错误消息,所以我不知道如何修复我的代码以通过测试用例。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:

        #find the number of shortest characters
        shortest_num = 0
        nums = [0] * len(strs)
        for i in range(len(strs)):
            nums[i] = len(strs[i])
            shortest_num = min(nums)

        l1 = strs[0]
        l2 = strs[1]
        l3 = strs[2]


        for j in range(shortest_num):
            tmp = ""
            while l1[j] == l2[j] and l2[j] == l3[j]:
                tmp += l1[j]
            candidate.append(tmp)

        print(max(candidate))

错误信息

Time Limit Exceeded

最佳答案

当您没有以 Good Time 复杂度编写代码时,就会出现此错误。 当 Leetcode 系统以更大的输入运行你的代码时,你的代码没有在最佳时间运行。 可能有一些已知的算法可以解决您的问题陈述。在互联网上搜索问题陈述,您会找到一些解决此问题的算法。

关于python - 如何解决leetcode中超过时间限制的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57931883/

相关文章:

Python 用字典值替换字符串

python - 需要为 smartsheet-python-sdk 和 PyInstaller 创建一个钩子(Hook)

Python:将字典列表转换为列表列表

regex - 在 MongoDB 集合中查找正则表达式数组的匹配项

python - 如何在不下载服务帐户凭据的情况下从 Google Compute Engine 和本地验证 Google API(Google Drive API)?

python - 在 Python ctypes 中加载 C 标准库的可移植方法

java - 将 Jackson for JSON View 与 Spring 2.5 集成

Java NIO 与 DotNet IO 性能对比

python - 如何使用 Selenium 和 xpath 在 Google 登录页面中选择电子邮件或电话字段?

python - 在python中从键盘读取原始输入