leetcode【14题】Longest Common Prefix
2024-10-16 06:58:50
题目:Longest Common Prefix
内容:
Write a function to find the longest common prefix string amongst an array of strings.
编写一个函数来查找字符串数组中最长的公共前缀字符串。
理解题目:
如数组 ["a", "b"] 最长的公共前缀字符串是 “”;
如数组 ["aa", "aa"] 最长的公共前缀字符串是 “aa”;
如数组 ["abc", "abcd"] 最长的公共前缀字符串是 “abc”。。。
解题思路
1 如果数组为空,则最长公共前缀为""; 2 如果数组不为空:
(1)找出字符串数组中长度最短的字符串min,其长度为min_len; 因为最长的公共前缀长度不会超过min_len;
(2)遍历数组,将min位置为[i] 的字符 和 数组中其他字符串位置为[i]的字符 比较;
如果不相等,则最长公共前缀为 min的前i个字符;
如果都相等,则最长公共前缀为 min。
Go语言实现
func longestCommonPrefix(strs []string) string { if len(strs) == {
return ""
} min_len := len(strs[])
index :=
for i:=; i<len(strs); i++ {
if len(strs[i]) < min_len {
min_len = len(strs[i])
index = i
}
} for j:=; j<len(strs[index]); j++ {
for k:=; k<len(strs); k++ {
if strs[index][j] != strs[k][j]{
return strs[index][:j]
}
}
}
return strs[index]
}
看一下耗时:
Python3实现
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
shortstr = min(strs, key=len)
for i, cha in enumerate(shortstr):
for other in strs:
if other[i] != cha:
return shortstr[:i]
return shortstr
看一下耗时:
是不是感觉go要快很多,Python更优雅?
最新文章
- 超简单——自己搭建ftp服务器
- tp5 model 中的类型转换
- 在Winform开发中使用日程控件XtraScheduler(2)--深入理解数据的存储
- 做中学之Vim实践教程
- 深入JVM-java虚拟机的基本结构
- ant学习
- WPF:ListView数据绑定及Style
- [wordpress]后台自定义菜单字段和使用wordpress color picker
- SWFUpload无刷新文件批量上传
- 洛谷 [P2764]最小路径覆盖问题
- codeblocks设置背景主题
- Ubuntu下安装Pycharm出现unsupported major.minor version 52.0
- C++系列总结——volatile关键字
- 微信小程序--家庭记账本开发--05
- jvm调优-从eclipse开始
- Unity中的GC以及优化
- 【转】android中的数据存取-方式一:preference(配置)
- chattr lsattr
- MyEclipse自带且常用的快捷键和自己定义的快捷键方法步骤
- CSS的基本使用
热门文章
- Hibernate Error: a different object with the same identifier value was already associated with the session
- Eventlog控件的使用
- nyoj281 整数中的1(二) 数位DP
- react——一个todolist的demo
- jQuery手机发送验证码倒计时代码
- RS232 3线制与7线制的区别
- mysql常用基础操作语法(六)--对数据排序和限制结果数量的条件查询【命令行模式】
- HashMap和Hashtable的异同点
- String getProperty(String key, String def)
- Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column &#39;content&#39; a