python - Python 最长公共(public)前缀

标签 python

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

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]

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

最佳答案

friend ,请尝试使其尽可能“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中可能吗?是的。使用 zip()

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)

关于python - Python 最长公共(public)前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60842684/

相关文章:

python - 使用Python评估html表中的图像

python - 如何从 URL 获取参数到身份验证函数? (Python、 flask )

python - 获取图中唯一状态的数量

python - 使用python的数据格式?

python - 如何连接序列化器(DjangoRestFramework)中的字段?

python - 将零值转换为 Pandas 中的空单元格

python - 可以打开/显示/呈现 headless (headless) Selenium session 吗?

python - Django 国际化 (i18n) lint 检查器?告诉我什么还没有 _( )'ed or {% trans %}' ed

python - Python中简单的模糊字符串匹配算法是什么?

python - 是否可以为 python 入口点定义层次结构?