我正在尝试找出一个简单的 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/