首页 > 编程语言 > 详细

leetcode-python-最长公共前缀

时间:2021-05-31 21:20:49      阅读:21      评论:0      收藏:0      [点我收藏+]

第一轮刷题解法:

1)如果长度为1,返回第一个字符串;如果存在空,返回空;否则长度递增,逐一比较,有不同则返回当前前缀。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        count_prefix = 1
        if len(strs) == 1:
            return strs[0]
        if ‘‘ in strs:
            return ‘‘
        while count_prefix <= len(strs[0]):
            temp = strs[0][0:count_prefix]
            for i in range(1,len(strs)):
                if strs[i][0:count_prefix] != temp: 
                    if count_prefix == 1:
                        return ‘‘
                    else:
                        return strs[0][0:count_prefix-1]
            count_prefix +=1
        return strs[0][0:count_prefix-1]

2)开挂,os库寻找公共前缀

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        import os
        return os.path.commonprefix(strs)

 

leetcode-python-最长公共前缀

原文:https://www.cnblogs.com/cbachen/p/14832328.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!