繁体   English   中英

Leetcode 问题 14. 最长公共前缀 (Python)

[英]Leetcode problem 14. Longest Common Prefix (Python)

我试图解决这个问题(你可以在这里阅读描述: https://leetcode.com/problems/longest-common-prefix/ )下面是我想出的代码。 它给出strs列表中第一个字符串的prefix值,并将前缀与列表中的每个字符串进行比较,弹出所有不相等的字符。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        prefix = strs[0][0]
        for i in range(len(strs)):
            for j in range(len(prefix)):
                if strs[i][j] != prefix[j]:
                    prefix.pop(prefix[j])
        return prefix

但是这段代码在第一个测试用例中失败了,其中strs = ["flower","flow","flight"] Expected output is "fl" ,而我的代码只返回"f"我正在努力寻找问题所在我的解决方案。 也许你能帮忙?

zip并行迭代字符:

strs = ["flower", "flow", "flight"]

n = 0
for chars in zip(*strs):
    if len(set(chars)) > 1:
        break
    n += 1

# length
print(n) # 2

# prefix
print(strs[0][:n]) # fl

与使用itertools.takewhile的单行程序类似的方法:

from itertools import takewhile

prefix = ''.join([x[0] for x in takewhile(lambda x: len(set(x)) == 1, zip(*strs))])

或者,您可以尝试使用os - commonprefix 中的库:(自 Python 3.5+ 起可用)


def longestCommonPrefix(self, strs: List[str]) -> str:
        return os.path.commonprefix(strs)


strs = ["flower","flow","flight"]
print(longestCommonPrefix(strs))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM