leetcode 腾讯精选练习(50 题)14.最长公共前缀

原题目

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

思路

假设结果字符串就是第一个字符串,然后遍历后面的字符串,和第二个字符串逐个字符比较,相同的前缀作为结果字符串,然后和第三个字符串比较……

第一遍解法
class Solution:
    def longestCommonPrefix(self, strs):
        res = strs[0]
        ans = ''
        for i in range(1, len(strs)):
            j = 0
            while strs[i][j] == res[j] and j < min(len(res), len(strs[i])):
                j += 1
            ans = res[:j]
        return ans

j 加 1 以后超出字符串下表最大值运行提示字符串下表溢出

网上好的解法
	# 只要有一个字符串的字符不相等剩下的字符串相等也无效
	# 因此只需要和最长的字符串进行比较就能知道整个字符串列表的最长公共前缀
    def longestCommonPrefix(self, strs):
        if not strs: return ""
        s1 = min(strs)
        s2 = max(strs)
        for i,x in enumerate(s1):
            if x != s2[i]:  
                return s2[:i]
        return s1
	#利用python的zip函数,把str看成list然后把输入看成二维数组
	#左对齐纵向压缩,然后把每项利用集合去重
	#之后遍历list中找到元素长度大于1之前的就是公共前缀
	def longestCommonPrefix(self, strs):
        if not strs: 
        	return ""
        ss = list(map(set, zip(*strs)))
        res = ""
        for i, x in enumerate(ss):
            x = list(x)
            if len(x) > 1:
                break
            res = res + x[0]
        return res
自己可以改进的地方

最简代码
class Solution:
    def longestCommonPrefix(self, strs):
        if not strs:
            return ''
        shortest = min(strs, key=len)
        longest = max(strs, key=len)
        for i, ch in enumerate(shortest):
            if ch != longest[i]:
                return shortest[:i]
        return shortest
获得的思考
  1. max()函数、min() 函数的使用,第二个key 参数的设置

python奇技淫巧——max/min函数的用法

  1. enumerate() 函数的使用,同时列出数据和下标
>>>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')]
  1. zip() 函数的使用
strs = ["flower","flow","flight", "abandon"]
for i in zip(*strs):
    print(i)
输出:
('f', 'f', 'f', 'a')
('l', 'l', 'l', 'b')
('o', 'o', 'i', 'a')
('w', 'w', 'g', 'n')
  1. map() 函数
map(function, iterable, ...)

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值