Leetcode Python刷题笔记-14.最长公共前缀

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

题目:最长公共前缀

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

示例 1:

输入: [“flower”,“flow”,“flight”]
输出: “fl”

示例 2:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
解法来自暴躁老哥在线刷题的博客

解法一:

import os
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """        
        return os.path.commonprefix(strs)
知识复习:os.path() 模块

os.path.commonprefix(list):返回list(多个路径)中,所有path共有的最长的路径

解法二:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """        
        if not strs:
            return ""
        l = [len(word) for word in strs]
        min_l = min(l) #确定最短的单词长度,以免后面循环超出某些单词长度
        
        for index, item in enumerate(strs[1:]):
            i = 0
            while(i < min_l and item[i] == strs[0][i]): #检查每个str中最多几个前部元素和第一个单词吻合
                i += 1
            min_l = min(min_l, i) #检查完毕后需要更新min_l,保持min_l是所有longestCommonPrefix中的最小值   
        return strs[0][:min_l]  #循环结束后返回longestCommonPrefix

如果strs中有n个字符串,所有单词最大长度为m,那么复杂度为O(m*n)

知识复习:

min() 方法返回列表元素中的最小值。
语法:min(list)
注意这里是for和while嵌套的循环

解法三:

用ascii排序后,不用盲目循环比较。复杂度为O(n)。

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """        
        if not strs:
            return "" # 要考虑strs为空的情况,因为此时不能进行min(strs) 操作
        mins = min(strs) 
        maxs = max(strs)
        
        for index, letter in enumerate(mins): # 逐个取出最小字符串中的每个字母
            if maxs[index] != mins[index]: #比较最大的字符串和最小的字符串的这个字母,直到出现不匹配的字母
                return mins[:index] #如果有单词不匹配,那么返回前面匹配的字母
        return mins #否则,从头到尾都是匹配的,那么返回mins
知识复习:

python里的字符串可以通过ascii形式比较,即字母顺序排列。如下面输出分别为’flight’和’flower’

strs = [“flower”,“flow”,“flight”]
min(strs)
max(strs)

解法四:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs: # 判断strs是否empty
            return ""
        
        strs.sort()
        res = ""
        
        for x, y in zip(strs[0], strs[-1]): # zip函数来组合最大字符串和最小字符串。
        #strs = ['flight','flow', 'flower']
		#zipped = zip(strs[0], strs[-1])
		#print(list(zipped))
        # 得到[('f', 'f'), ('l', 'l'), ('i', 'o'), ('g', 'w'), ('h', 'e'), ('t', 'r')]
            if x == y:
                res += x
            else:
                break
        
        return res
知识复习:

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
我们可以使用 list() 转换来输出列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。(来自菜鸟教程)

a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b) # 返回一个对象
list(zipped) # list() 转换为列表
Out: [(1, 4), (2, 5), (3, 6)]
list(zip(a,c)) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]

判断list, string等是否为空的方法:if not list/string (empty), if list (not empty)
或者len(list) == 0

你可能感兴趣的:(Leetcode Python刷题笔记-14.最长公共前缀)