python找出最长公共前缀

#找出最长公共前缀
strs = ["dog","racecar","car"] #"" strs = ["flower","flow","flight"] #"fl"
方法一:
lenstrs=[]
for i in strs:
    lenstrs.append(len(i))
lenstrs=sorted(lenstrs,reverse=False)
print(lenstrs[0])
strlistzong=[]
#3 代表列表中最短的字符串
for j in range(3):
    strlist = []
    for i in strs:
        strlist.append(i[j])
    strlist=sorted(strlist)
    if strlist[0]==strlist[-1]:
        strlistzong.append(strlist[0])
print(‘‘.join(strlistzong))

 方法二:

 

def longestCommonPrefix(strs):
    if not strs: return ""
    #s1是从小到头排序 s2从大到小排序
    s1 = min(strs)
    s2 = max(strs)
    for i, x in enumerate(s1):
        # i是索引  x是数据  
        print(i,x)
        if x != s2[i]:
            return s2[:i]
    return s1
print(longestCommonPrefix(strs))        

 方法三:

#zip 组成2维数组
print(list(zip(*strs)))
#去重
setstrs=list(map(set,(zip(*strs))))
print(setstrs)
resstrs=‘‘
for x in setstrs:
    if len(list(x))==1:
        resstrs += list(x)[0]
print(resstrs)

  

python找出最长公共前缀

上一篇:nginx.conf完整配置实例


下一篇:Linux 给指定python项目创建虚拟环境