Leetcode笔记-14 最长公共前缀

14 最长公共前缀

题目描述

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

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

思路

1、string.sort()排序,因为都是小写字母,所以按照ASCII值排序,所以只需要寻找第一个和最后一个字串的公共前缀即可
2、利用zip和set,代码及思路参考自leetcode评论区,链接见结尾

代码

class Solution:
    def longestCommonPrefix(self, strs: list[str]) -> str:
        
        if len(strs) == 0:
            return ""
        strs.sort()
        length = 0
        for i in range(len(strs[0])):
            if strs[0][i]==strs[-1][i]:
                length+=1
            else:
                return strs[0][0:length]
        return strs[0][0:length]


class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        res = ""
        for tmp in zip(*strs):
            tmp_set = set(tmp)
            if len(tmp_set) == 1:
                res += tmp[0]
            else:
                break
        return res

作者:powcai
链接:https://leetcode-cn.com/problems/longest-common-prefix/solution/duo-chong-si-lu-qiu-jie-by-powcai-2/

你可能感兴趣的:(leetcode,leetcode,算法,职场和发展)