Python3 实现 LeetCode 14最长公共前缀

问题描述

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。

  • 示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
  • 示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
  • 说明:
所有输入只包含小写字母 a-z。

问题解答

方法一 将字符串列表排序,从最短的两个字符串取得其公共前缀,然后横向扫描得到结果

   def longestCommonPrefix(self, strs: List[str]) -> str:
        if strs != []:
            len_lst = []
            #构建字符串及其字符串长度的列表,稍后看到第二种方法发现这是画蛇添足
            for item in strs:
                len_lst.append([len(item), item])
            #对得到列表进行排序,从最短的两个字符串开始取得公共前缀
            len_lst.sort()
            common_part = len_lst[0][1]
            #依次遍历字符串列表,得出最终公共前缀
            for i in range(1, len(len_lst)):
                while common_part  != len_lst[i][1][:len(common_part)]:
                    common_part = common_part[:-1]
        else:
            common_part = ""
        return common_part
    

执行用时 : 52ms


思考

方法一是基于如下思考:公共前缀是所有字符串共有的, 那么从最短的两个字符串开始找公共前缀相对来说会简便一些。如下例子,是一个排好序的字符串列表。

[‘aacbc’, ‘aacdde’, ‘aacdfe’, ‘aacpo’, ‘ab’]

在python中字符串排序,即字符串比较是按照单个字符进行比较的。意味着在排序的过程中,其实已经在实现寻找公共前缀的功能。基于此,有如下方法二。


方法二 字符串排序,比较"最大最小"即可

    def longestCommonPrefix(self, strs: List[str]) -> str:
        if strs != []:
            commonprefix = min(strs)
            str_max = max(strs)
            #比较最大最小字符串,得到其公共前缀即为整个字符串列表的公共前缀
            while commonprefix != str_max[:len(commonprefix)]:
                commonprefix = commonprefix[:-1]
            
            #求公共前缀另一种实现    
            #commonprefix = ""
            #str_min = min(strs)
            #str_max = max(strs)
            #for i in range(len(min(strs))):
                #if str_min[i] == str_max[i]:
                    #commonprefix = commonprefix + str_min[i]
                #else:
                    #break
            
        else:
            commonprefix = ""
        return commonprefix

执行用时 : 50ms


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值