LeetCode-Python-14. 最长公共前缀

660 篇文章 23 订阅

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

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

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

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

说明:

所有输入只包含小写字母 a-z 。

第一种思路:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        return os.path.commonprefix(strs)

第二种思路:

先找到最短的单词的长度min_l,初始化公共前缀common为首元素的[: min_l]

然后从头开始对每个单词进行比较,比较过程中不断更新当前最长公共前缀的长度min_l, 和当前最长公共前缀common。

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        min_l = len(strs[0])
        for word in strs:
            min_l = min(min_l, len(word))
            
        common = strs[0][:min_l]
        # print common
        
        
        for index, item in enumerate(strs):
            i = 0
            while(i < min_l and item[i] == common[i]):
                i += 1
                
            min_l = min(min_l, i)
            common = common[:min_l]
            
        return common

第三种思路:

python里的字符串可以通过ascii的形式进行比较,所以只要找出最大的字符串和最小的字符串进行比较,就可以找到最长公共前缀。

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        
        mins = min(strs)
        maxs = max(strs)
        
        for index, item in enumerate(mins):
            if maxs[index] != mins[index]:
                return mins[:index]
            
        return mins

第四种思路:

跟第三种思路一样都利用了字符串的比较,但是额外用了zip函数来组合最大字符串和最小字符串。

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        
        strs.sort()
        res = ""
        
        for x, y in zip(strs[0], strs[-1]):
            if x == y:
                res += x
            else:
                break
        
        return res
                

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值