力扣刷题笔记:14. 最长公共前缀(zip(*list)妙用、牛逼坏了、完整题解代码及注释)

题目:

14、最长公共前缀

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

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

示例 1:

输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”

示例 2:

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

提示:

0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成

题解思路:

先使用zip(*li)对字符串数组进行元素打包,然后使用set()函数去重,如果去重后的元素长度为1,则是公共前缀。

题解python代码:

class Solution(object):
    def longestCommonPrefix(self, strs):
        s = ""
        # print(list(zip(*strs)))
        for i in list(zip(*strs)):
            ss = set(i)
            # print(ss)
            if len(ss) == 1:
                s += ss.pop()
            else:
                break  # 只要有一个不是一就跳出
        return s

在这里插入图片描述

作者:a-qing-ge
链接:https://leetcode-cn.com/problems/longest-common-prefix/solution/ziplistmiao-yong-niu-bi-pi-liao-by-a-qin-ul61/
来源:力扣(LeetCode)https://leetcode-cn.com/problems/longest-common-prefix/

猜你喜欢

转载自blog.csdn.net/weixin_44414948/article/details/113746669