【LeetCode】14. Longest Common Prefix Python3解法

题目描述:

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.

思路:

求最长前缀字符串,首先要找到最短的那个单词,最长前缀字符串的长度不会超过该单词。并且在这个最短单词上找到公共最长位置i,最后直接输出关于最短单词[:i]即可。

代码:

class Solution:
    def longestCommonPrefix(self, strs) -> str:
        if strs == None or strs == []: return ''
        shor = min(strs,key=len)
        i = 0
        flag = False
        while i < len(shor):
            char = shor[i]
            for s in strs:
                if s[i] != char:
                    flag = True
            if flag:
                break
            i += 1
        return shor[:i]

知识点:

max/min函数的技巧和应用:
初级:

print(max(1,2,5,2))

output: 5

a = [1,2,5,2]
print(max(a))

output: 5
中级:

a=[1,-2,3,-10,0]
print(max(a,key=abs))

output: -10
高级

#求商品最便宜的是哪个
prices = {
    'A':123,
    'B':450.1,
    'C':12,
    'E':444,
}
k = min(prices,key=lambda v:prices[v])
print(k)

output: C

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值