首页 > 解决方案 > Python 的最长公共前缀

问题描述

我试图找出一个简单的 leetcode 问题,但我不知道为什么我的答案不起作用。问题:编写一个函数来查找字符串数组中最长的公共前缀字符串。如果没有公共前缀,则返回一个空字符串“”。我的代码:

shortest=min(strs,key=len)
strs.remove(shortest)
common=shortest
for i in range(1,len(shortest)):
    comparisons=[common in str for str in strs]
    if all(comparisons):
        print(common)
        break
    else:
        common=common[:-i]

当列表中的字符串长度相同但适用于其他情况时,上述试验不起作用。非常感谢。

标签: python

解决方案


朋友,尽量让它像“pythonic”一样。就像你在现实生活中一样。

在现实生活中你看到了什么?您会看到单词,也许会寻找最短的单词并将其与所有其他单词进行比较。好的,让我们这样做,让我们找到最长的单词,然后找到最短的单词。

首先我们创建一个空字符串,其中两个字符串中相同的字符将被存储

prefix = ''
#'key=len' is a necesary parameter, because otherwise, it would look for the chain with the highest value in numerical terms, and it is not always the shortest in terms of length (it is not exactly like that but so that it is understood haha)
max_sentense = max(strings, key=len)
min_sentense = min(strings, key=len)

好的,现在我们在现实生活中会做什么?从一开始就一个接一个地循环,在python中可以吗?是的。带拉链()

for i, o in zip(max_sentense, min_sentense):

'i' 将通过最长的字符串,'o' 将通过最短的字符串。

好的,现在很容易,我们只需要在 'i' 和 'o' 不同时停止遍历它们,也就是说,它们不是同一个字符。

for i, o in zip(max_sentense, min_sentense):

        if i == o:
            prefix += i
        else:
            break

完整代码:

prefix = ''


    max_sentense = max(strings, key=len)
    min_sentense = min(strings, key=len)

    for i, o in zip(max_sentense, min_sentense):

        if i == o:
            prefix += i
        else:
            break
print(prefix)

推荐阅读