注册 登录
编程论坛 Python论坛

一起刷leetcode:最长公共前缀

虫眼 发布于 2022-10-19 11:59, 1035 次点击
编写一个函数来查找字符串数组中的最长公共前缀。

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

示例 1:

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

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

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
3 回复
#2
虫眼2022-10-19 12:29
> 2022/10/19 11:36:38   
解答成功:
    执行耗时:40 ms,击败了57.42% 的Python3用户
    内存消耗:15.1 MB,击败了45.23% 的Python3用户
#3
虫眼2022-10-21 10:31
程序代码:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        s = ""
        num = 0
        while True:
            sum_str = dict()
            try:
                for i in strs:
                    if sum_str.get(i[num]):
                        sum_str[i[num]] += 1
                    else:
                        sum_str[i[num]] = 1
            except IndexError:
                break
            num += 1
            if len(sum_str) == 1:
                s += [x for x in sum_str][0]
            elif len(sum_str) != 1 and s is not None:
                break
        return s

#4
sssooosss2022-11-02 09:23
共同学习
1