LeetCode 笔记十 最长共同前缀


这两天有点事情,晚上没有时间刷题,但不想落下啊!

Longest Common Prefix

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

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.

Code

一开始想歪了,取出了最长跟最短的字符串进行对比:

class Solution:
    def longestCommonPrefix(self, strs):
        if len(strs) == 0:
            return ''
        elif len(strs) == 1:
            return strs[0]
        
        minStr = min(strs, key = len)
        maxStr = max(strs, key = len)
        r = ''
        for i, j in zip(minStr, maxStr):
            if i == j:
                r += i
            else:
                break
                
        del minStr, maxStr
        return r

结果当然报错了:

input : ["flower","flow","flight"]
Output : "flow"
Expected : "fl"

后来发现直接对strs进行排序后再作对比就ok了:

class Solution:
    def longestCommonPrefix(self, strs):
        if len(strs) == 0:
            return ''
        elif len(strs) == 1:
            return strs[0]
        strs.sort()
        r = ''
        for i, j in zip(strs[0], strs[-1]):
            if i == j:
                r += i
            else:
                break
        return r

结果:

118 / 118 test cases passed.
Runtime: 36 ms
Memory Usage: 13.7 MB

Runtime: 36 ms, faster than 91.40% of Python3 online submissions for Longest Common Prefix.
Memory Usage: 13.7 MB, less than 6.67% of Python3 online submissions for Longest Common Prefix.

国庆期间一直在做一个理论的算法推导,秃头了难顶呀。这两天又开始准备一个CCF的比赛,冲吧~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值