python - 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]
当列表中的字符串长度相同但适用于其他情况时,上述试验不起作用。非常感谢。
解决方案
朋友,尽量让它像“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)
推荐阅读
- vue.js - `nuxt` 与 `nuxt generate`:未定义要求
- javascript - 从文本中提取某个数字
- visual-studio-code - vscode - 搜索时如何自动启用正则表达式?
- javascript - React-Native 将多个设备连接到一个打包器
- c++ - 如何更新 .h 文件中的布尔值?
- python - 难以理解 Python 中的返回值和函数参数
- c# - Xamarin Forms - 如何创建简单的订单列表/购物车?
- c# - WPF MVVM - 从子视图模型更新 MainView 的 Datagrid
- hyperledger-fabric - 使用 Cryptogen 生成中间 CA 并启动中间结构 CA 服务器
- javascript - 一次将相同的道具传递给子元素