leetcode 14 最长公共前缀

题目描述

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

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

示例 1:

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

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

解题思路一

简单朴素,逐一比较就行。

(1)首先可以确定的是最长前缀的长度小于等于列表中最短字符串的长度。

res <= min([len(each) for each in strs]

 

(2)找到列表中最短字符串,然后以它为标准和其它(包括它自己)列表中的字符串元素进行比较

1、遍历的过程中,如果有一个列表元素没有匹配上,即当前字符不是所有列表字符串元素的前缀,

结束遍历,返回满足条件的前缀。

2、如果当前字符是所有列表字符串元素的前缀,把当前字符加入到前缀中去,遍历下一个字符

3、重复1、2过程,返回满足条件的前缀。

完整代码

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        
        if len(strs) < 1:
            return ''
        length = [len(each) for each in strs]
        idx = length.index(min(length))
        template = strs[idx]
        res = ''
        for i in range(len(template)):
            c = template[i]
            for index,word in enumerate(strs):
                if word[i] != c:
                    return res
            res += c 
        return res 

解题思路二 

利用zip、和set。

(1)通过zip操作把列表解析成单字符元组

temp = zip(*(strs))

strs = ['abc','efg','jkl']

temp=['a','b','c'
      'e','f','g'
      'j','k','l']
实际上是 [('a','e','j'),('b','f','k'),('c','g','l')]


相当于把原来的字符串按列铺开。

(2)通过set操作,判断每个经过zip解析的元组中元素的数目。

if len(set(c)) == 1:

    res += c[0]
else:
    break



完整代码

 

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        
        res = ''

        for c in zip(*(strs)):
            if len(set(c)) == 1:
                res += c[0]
            else:
                break

        return res 
        

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nobrody

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值