当前位置:网站首页>【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,喜欢的可以点个收藏和关注,我们下次再见!
边栏推荐
- 二、mock平台的扩展
- 远程办公对我们的各方面影响心得 | 社区征文
- linux下配置Mysql授权某个用户远程访问,不受ip限制
- 寒门再出贵子:江西穷县考出了省状元,做对了什么?
- LeetCode 2. Add two numbers
- SQL solves the problem of continuous login deformation holiday filtering
- 亚马逊云科技 Community Builder 申请窗口开启
- Take you ten days to easily complete the go micro service series (I)
- Role and function of uboot
- Routing mode: hash and history mode
猜你喜欢
PCL point cloud image transformation
【征文活动】亲爱的开发者,RT-Thread社区喊你投稿啦
LeetCode 2. Add two numbers
串口控制舵机转动
寒门再出贵子:江西穷县考出了省状元,做对了什么?
TCP拥塞控制详解 | 2. 背景
小鹏P7雨天出事故安全气囊没有弹出 官方回应:撞击力度未达到弹出要求
sql解决连续登录问题变形-节假日过滤
L'explosion de John utilise l'encodage d'entrée par défaut: UTF - 8 Loaded 1 password Hash (bcrypt [blowfish 32 / 64 X3])
路由模式:hash和history模式
随机推荐
Leetcode1380: lucky numbers in matrix
Seal Library - installation and introduction
lsf基础命令
What if the win11 app store cannot load the page? Win11 store cannot load page
什么是泛型?- 泛型入门篇
john爆破出現Using default input encoding: UTF-8 Loaded 1 password hash (bcrypt [Blowfish 32/64 X3])
ROW_NUMBER()、RANK()、DENSE_RANK区别
Cloud native cicd framework: Tekton
Yyds dry goods inventory has not revealed the artifact? Valentine's Day is coming. Please send her a special gift~
VMware install win10 image
隐私计算技术创新及产业实践研讨会:学习
深度学习图像数据自动标注[通俗易懂]
大厂面试总结大全
How openharmony starts FA of remote devices
Global and Chinese markets of stainless steel surgical suture 2022-2028: Research Report on technology, participants, trends, market size and share
jsp 和 servlet 有什么区别?
Take you ten days to easily complete the go micro service series (I)
一文看懂:数据指标体系的4大类型
LeetCode 4. 寻找两个正序数组的中位数(hard)
R及RStudio下载安装教程(超详细)