当前位置:网站首页>【Leetcode】14. 最长公共前缀
【Leetcode】14. 最长公共前缀
2022-07-02 14:18:00 【wangzirui32】
博文作者 wangzirui32
喜欢的可以 点赞 收藏 关注哦~~
本文首发于CSDN,未经许可禁止转载
1. 题目描述

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-common-prefix/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题思路
我们找到列表中最小长度的字符串,进行循环,然后每一次循环检测是否与其他字符串前缀相同,如相同结果存入result中,循环结束后返回最大前缀。
3. 代码实现
Code:
class Solution:
def longestCommonPrefix(self, strs) -> str:
min_length_str = min(strs, key=lambda s: len(s))
result = ""
for i in range(1, len(min_length_str)+1):
swith = min_length_str[:i]
if all([k.startswith(swith) for k in strs]):
result = swith
return result
我来解析其中比较重要的代码:
min(strs, key=lambda s: len(s))以字符串的长度为参照,选出最小字符串swith = min_length_str[:i]获取索引i之前的前缀all([k.startswith(swith) for k in strs])检测其他字符串前缀是否都相同。
4. 最终结果

好了,今天的课程就到这里,我是wangzirui32,喜欢的可以点个收藏和关注,我们下次再见!
边栏推荐
- Global and Chinese market of discharge machines 2022-2028: Research Report on technology, participants, trends, market size and share
- LeetCode 2. Add two numbers
- Executive engine module of high performance data warehouse practice based on Impala
- PhD Debate-11 预告 | 回顾与展望神经网络的后门攻击与防御
- Configure ARP table entry restrictions and port security based on the interface (restrict users' private access to fool switches or illegal host access)
- jsp 和 servlet 有什么区别?
- Global and Chinese market of switching valves 2022-2028: Research Report on technology, participants, trends, market size and share
- 深度学习图像数据自动标注[通俗易懂]
- SQL solves the problem of continuous login deformation holiday filtering
- MySQL port
猜你喜欢

What if the win11 app store cannot load the page? Win11 store cannot load page

Hard core! One configuration center for 8 classes!

渗透工具-内网权限维持-Cobalt strike

How openharmony starts FA of remote devices

大厂面试总结大全

linux安装postgresql + patroni 集群问题

PWM controlled steering gear

【征文活动】亲爱的开发者,RT-Thread社区喊你投稿啦

电脑自带软件使图片底色变为透明(抠图白底)

The login box of unity hub becomes too narrow to log in
随机推荐
js删除字符串中的子串
Cell: Tsinghua Chenggong group revealed an odor of skin flora. Volatiles promote flavivirus to infect the host and attract mosquitoes
pwm呼吸燈
unity Hub 登錄框變得很窄 無法登錄
[error record] error -32000 received from application: there are no running service protocol
LeetCode 1. 两数之和
618深度複盤:海爾智家的制勝方法論
大廠面試總結大全
DGraph: 大规模动态图数据集
寒门再出贵子:江西穷县考出了省状元,做对了什么?
Ap和F107数据来源及处理
你想要的宏基因组-微生物组知识全在这(2022.7)
Talk about an experience of job hopping and being rejected
618 reprise en profondeur: la méthode gagnante de la famille Haier Zhi
关于举办科技期刊青年编辑沙龙——新时代青年编辑应具备的能力及提升策略的通知...
July 1st gift: Yi Jingjie's "hundred day battle" ended perfectly, and the database of Guiyang bank was sealed in advance
pwm呼吸灯
只是巧合?苹果iOS16的神秘技术竟然与中国企业5年前产品一致!
go-zero微服务实战系列(八、如何处理每秒上万次的下单请求)
Cloud native cicd framework: Tekton