题目:
Write a function to find the longest common prefix string amongst an array of strings.
我的暴力解法:
def longestCommonPrefix(self, strs):
if not strs:
return ""
length = len(strs[0])
i = 1
while i <= length:
for s in strs:
if strs[0][:i] not in s or s.index( strs[0][:i]) != 0:
return strs[0][:i-1]
i+=1
return strs[0][:i-1]
参考:
法1:
python os.path模块中,os.path.commonprefix(list) #返回list(多个路径)中,所有path共有的最长的路径。
import os
return os.path.commonprefix(strs)
法2:
if not strs: #if strs = []
return("")
for i, letter_group in enumerate(zip(*strs)): #和空zip
if len(set(letter_group)) > 1:
return(strs[0][:i])
##if shortest string is the common prefix or strs contains ""
else:
return(min(strs))
知识点:
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
--------------新手刷题,仅用于自身记录,如有错误,欢迎指出---------------