刷题去WLB965 一起来刷题:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。

团长 · October 12, 2021 · Last by william replied at October 13, 2021 · 3068 hits

难度:简单
一起来刷题吧

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        #存在空串直接返回""
        if "" in strs :
            return ""
        #只有一个元素 
        elif len(strs)==1:
            return strs[0]
        #排序
        else:
            strs=sorted(strs,key=lambda x:len(x))
            #第一个拿出来 遍历它的每个元素和其他元素比较 直到不相等
            comm=""
            for i in range(len(strs[0])):
                commlist=[]
                for j in strs:
                    commlist.append(j[i])
                if len(set(commlist))==1:
                    comm +=j[i]
                else:
                    break
        return comm

原题链接:https://leetcode-cn.com/problems/longest-common-prefix/

共收到 2 条回复 时间 点赞


无脑爆破

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up