【问题标题】:Could any optimizations be made to this code to make it run faster?可以对此代码进行任何优化以使其运行得更快吗?
【发布时间】:2022-09-30 18:54:20
【问题描述】:

我已经完成了代码挑战的尝试,其中我必须找出单词列表之间的最长前缀。我认为(希望)我的解决方案还可以,但效率不够高,因此无法运行,有人可以建议对我的代码进行优化吗?非常感谢您的帮助,请忽略任何愚蠢的错误-我仍在学习:(。 单词是 [\"flower\",\"flow\",\"flight\"] 和 [\"dog\",\"racecar\",\"car\"]

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 0:
            return(\"\")
        if len(strs) == 1:
            return(strs[0])
        
        prefix = strs[0]
        wordLength = len(strs)
        
        for i in range(wordLength):
            
            while prefix != strs[i+1]:
                prefix = prefix[:-1]
                
            if len(prefix) == 0:
                return(\"\")
        return(prefix)
        
  • 请通过显示这两个列表的预期输出来澄清
  • 这段代码看起来有问题。例如,在for 循环中,i 的范围从0len(strs)-1。所以在最后一次迭代中,i+1len(strs),所以strs[i+1] 是一个越界引用。您可能希望将strs[i+1] 更改为strs[i],并将for 循环更改为for i in range(1, wordLength)
  • 但这似乎仍然不对。它修复了索引错误,但while 循环没有进行前缀比较。它正在减少 prefix 并且它匹配全部的字符串,而不是它的开头。你可能想要strs[i].startswith(prefix)
  • 在风格上,在 Python 中使用 return(val) 是不寻常的。只需使用return val。括号没有任何作用。

标签: python


【解决方案1】:

您可以通过使用生成器和内置 python 函数来改进运行时(因为它们是在 C 中执行的):

def longest_common_prefix(self, strs: List[str]) -> str:
    if len(strs) == 0:
        return ""
    
    prefix = strs[0]
    while prefix: # aka while prefix not empty
        if all(s.startswith(prefix) for s in strs):
            return s
        prefix = prefix[:-1]
    assert False, "this line should never be reached"

您通常也可以通过不重复检查您已经知道的字符来提高您的复杂性:

def longest_common_prefix(self, strs: List[str]) -> str:
    if len(strs) == 0:
        return ""
    shortest_str_len = min(len(s) for s in strs)
    for i in range(1, shortest_str_len):
        current_char = strs[0][i]
        if not all(s[i] == current_char for s in strs):
            return strs[0][:i-1]
    assert False, "this line should never be reached"

删除的第二种方法是 O(len(strs)*len(shortest_str) 而不是 O(len(strs)*len(shorest_str)^2)

【讨论】:

  • 你不能返回因为不在范围内
猜你喜欢
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
相关资源
最近更新 更多