leetcode14 ----最长公共前缀

本文介绍了一种在字符串数组中查找最长公共前缀的方法,通过示例展示了如何使用Python的zip()函数和集合操作实现这一功能。同时,还提供了一个利用max()和min()函数的替代解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个函数来查找字符串数组中的最长公共前缀。

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

示例 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值