我已经用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
答案 0 :(得分:0)
始终使用列表推导会更快。 例如,要获取字符串长度列表,请使用以下
lens = [len(x) for x in strs]
min_len = min(lens)