描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例1:
输入: ["flower","flow","flight"]
输出: "fl"
示例2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明
所有输入只包含小写字母 a-z
so easy的题
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# 字符串总个数
if len(strs) == 0:
return ""
index = 0
common_prefix = ""
# 从第一个字符串的第一个字符开始去试探
while True:
try:
ch = strs[0][index]
# 匹配每个字符串
for item in strs:
if item[index] != ch:
return common_prefix
# 继续往下试探
index += 1
common_prefix += ch
# 最短字符串到底了
except IndexError:
return common_prefix
plus
虽然是简单题,不过看到一位仁兄巧妙的用了python中的zip()
zip的特点
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9, 10]
zip(a, b, c) is =>
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
set((1, 1, 1)) = {'1'}
set((1, 1, 2)) = {'1', '2'}
于是代码就可以这样写了:
def longestCommonPrefix_use_zip(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = ''
for _, item in enumerate(zip(*strs)):
if len(set(item)) > 1:
return prefix
else:
prefix += item[0]
return prefix
古德古德。
作者地址:https://blog.csdn.net/github_37953781/article/details/73649713