leetcode 14-最长公共前缀 python

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

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

示例 1:

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

示例 2:

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

可以使用enumerate()函数进行对比。enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']

>>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

>>> list(enumerate(seasons, start=1)) # 下标从 1 开始 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

PS:这里可以设置下标,默认是从0开始

普通的 for 循环

>>>i = 0

>>> seq = ['one', 'two', 'three']

>>> for element in seq: 

             print i, seq[i] 

             i +=1

... 0 one 1 two 2 three

for 循环使用 enumerate

>>>seq = ['one', 'two', 'three']

>>> for i, element in enumerate(seq):

             print i, element

... 0 one 1 two 2 three

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ''
        s1 = min(strs)
        s2 = max(strs)
        for i,element in enumerate(s1):
            if element != s2[i]:
                return s1[:i]
        return s1

 

你可能感兴趣的:(python基础)