【发布时间】:2022-02-12 01:40:18
【问题描述】:
我在 LeetCode 中编写了最长公共前缀的代码,但返回“超出时间限制”。
没有具体的错误信息,所以我不知道如何修复我的代码以通过测试用例。
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
【问题讨论】:
-
超过时间限制意味着他们在更大的输入上运行您的代码,并且代码很慢。您需要优化代码以降低运行时复杂性。
-
请注意,如果不知道您的实际任务是什么,则很难帮助您优化代码。
标签: python python-3.x performance