编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
解法1:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
res=""
if len(strs) ==0:
return ""
for each in zip(*strs):
if len(set(each))==1:
res += each[0]
else:
return res
return res
zip()函数在python3的使用:
1
a4=["abcs","basd","sefc","ascd"]
zip1=zip(*a4)
for i in zip1:
print(i)
输出
('a', 'b', 's', 'a')
('b', 'a', 'e', 's')
('c', 's', 'f', 'c')
('s', 'd', 'c', 'd')
2
a4=["abcs","basd","sefc","ascd"]
zip1=zip(a4)
for i in zip1:
print(i)
输出
('abcs',)
('basd',)
('sefc',)
('ascd',)
3
a1=[1,2,3]
a2=[4,5,6]
a3=[7,8,9]
a4=["a","b","c","d"]
zip1=zip(a1,a2,a3,a4)
for i in zip1:
print(i)
输出
(1, 4, 7, 'a')
(2, 5, 8, 'b')
(3, 6, 9, 'c')
4
a1=[1,2,3]
a2=[4,5,6]
a3=[7,8,9]
a4=["a","b","c","d"]
zip1=zip(*(a1,a2,a3,a4))
for i in zip1:
print(i)
输出
(1, 4, 7, 'a')
(2, 5, 8, 'b')
(3, 6, 9, 'c')
解法2:参考leetcode 该题目评论内容
利用python的max()、min()函数,字符串按照ascii码进行比较。因此可利用这种性质进行编码:
def logestComminPrefix(self,strs):
if not strs:
return ''
s1 = min(strs)
s2 = max(strs)
for i,x in enumerate(s1):
if x != s2[i]:
return s2[:i]
return s1