您的位置:首页 > 编程语言 > Python开发

leetcode-腾讯精选练习(50 题)python #14最长公共前缀

2019-05-12 20:29 597 查看

leetcode-腾讯精选练习(50 题)python #14最长公共前缀
题目来源:https://leetcode-cn.com/problemset/50/
编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例 1:

输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:

输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:

所有输入只包含小写字母 a-z 。

class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
r = [len(set(c)) == 1 for c in zip(*strs)] + [0]
return strs[0][:r.index(0)] if strs else ''

Python zip() 函数:
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象。zip(*) 可理解为解压,返回原矩阵。
a = [1,2,3]
b = [4,5,6]
zip_new = zip(a,b)
zip_new_list = list(zip_new)
[(1, 4), (2, 5), (3, 6)]
a1,b1 = zip(*zip(a,b)
list(a1)
[1,2,3]
list(b1)
[4,5,6]
Python set() 函数:
set() 函数创建一个无序不重复元素集.
aa = ‘abcdef’
bb = set(aa)
print(bb)
{‘d’, ‘e’, ‘a’, ‘c’, ‘f’, ‘b’}
Python index()方法:
检测字符串中是否包含子字符串 str
aa = ‘abcdef’
bb = ‘bc’
print(aa.index(bb))
1

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: