gpt4 book ai didi

python - 对任意长度的 List[str] 进行多次相等测试来解决 LongestCommonPrefix

转载 作者:行者123 更新时间:2023-12-01 08:04:54 25 4
gpt4 key购买 nike

我正在研究Longest Common Prefix - LeetCode

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z

我设计了这样的解决方案

def longestCommonPrefix(self, strs: List[str]) -> str:
res = ''
#base case 1
if len(strs) < 1: return res
size = min(len(s) for s in strs)
#base case 2 one of them is empty
if size < 1: return res

#iteration case
for i in range(size):
if strs[0][i] == strs[1][i] == str[2][i]:
res += strs[0][i]
else: break

if if strs[0][i] == strs[1][i] == strs[2][i]: 将元素添加到 res

但是,在我的解决方案中,strs的长度固定为3,给定的条件是strs的任意长度

怎么写这样的表达式

            if strs[0][i] == strs[1][i] == str[s2][i] ....strs[length-1][i]:

对于其他解决方案:

    #iteration case 
for i in range(size):
prefix = strs[0][i]
for j in range(1, len(strs)): #check the chain equal
if strs[j][i] != prefix: break
else:
res += prefix

return res

最佳答案

您可以通过allzip来实现这一点,试试这个:

if all(str1[i] == str2[i] for str1, str2 in zip(strs[:-1], strs[1:])):

希望对您有帮助,如有疑问请评论。 :)

关于python - 对任意长度的 List[str] 进行多次相等测试来解决 LongestCommonPrefix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55585499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com