LeetCode-14 longest common prefix

题目:

Write a function to find the longest common prefix string amongst an array of strings.

解题思路:

恩新手复习下zip,set好了……

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        #若字符串为空,最长公共前缀为空
        if not strs:
            return ""
        """
        将字符串zip,例如:输入为strs = ["abc","abd","abcdt"]
        for index,ch in enumerate(zip(*strs))对应的index和ch为:
        0 ('a', 'a', 'a')
        1 ('b', 'b', 'b')
        2 ('c', 'd', 'c')
        每个index中的set(ch)对应为:
        {'a'}
        {'b'}
        {'c', 'd'}
        如果set的长度大于一,说明已经不再是公共前缀了,此时输出index之前的字符串
        """
        for index,ch in enumerate(zip(*strs)):
            if len(set(ch)) > 1:
                return strs[0][:index]
        else:#考虑只有一个字符串的情况:输出最短的字符串

            return min(strs)


discuss中还提供了一种思路:

用的是迭代的思想,

class Solution:

    def lcp(self, str1, str2):
        i = 0
        while (i < len(str1) and i < len(str2)):
            if str1[i] == str2[i]:
                i = i+1
            else:
                break
        return str1[:i]

    # @return a string                                                                                                                                                          
    def longestCommonPrefix(self, strs):
        if not strs:
            return ''
        else:
            return reduce(self.lcp,strs)
reduce() 函数会对参数序列中元素进行累积。
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值