LeetCode专题-Python实现之第14题:Longest Common Prefix
相关代码已经上传到github:https://github.com/exploitht/leetcode-python
文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo
1、读题
Write a function to find the longest common prefix string amongst an array of strings.
很简单的一句话,寻找一个字符串数组的最大公共前缀字符子串
举个简单的例子,如下字符串列表:
['abc', 'abcd', 'abd']
的最大公共前缀是'ab'
2、解题
最简单粗暴的方式,遍历嘛,搞一个前缀,前缀从短变长,去匹配整个字符串数组,就能找到公共前缀。基于这种思路,有了如下代码:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# 空列表判断
if not strs:
return ''
# 取第一个字符串来寻找前缀
first_str = strs[0]
prefix = ''
for i in range(len(first_str)):
prefix = first_str[:i + 1]
# 如果strs中每一个字符串都是以prefix开头,那么prefix就是前缀
if all(map(lambda x: x.startswith(prefix), strs)):
continue
else:
break
else:
return prefix
return prefix[:-1]
3、第一次优化
上面这种实现方式用一次循环来取出一个前缀,然后循环遍历字符串数组判断前缀是否正确,也就是O(n2)的时间复杂度(n的平方)
能不能优化一点呢,思考有序比无序简单,是否可以先排序?Python的sorted函数排序性能可是杠杠的,Timsort算法在最坏情况也有n log n的表现,快排一般也是这个复杂度,但是最坏情况是n平方。
如果有序,怎样寻找前缀呢?观察一个有序的例子:['abcd','abce','abd','ad'],第一个和第二个比较,能够得到的子串一般相对较长,但是越往后呢,对了,不会变长,只会变短或者不变。也就是首尾对比就能够得到结果。于是乎有了下面解题方式:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# 如果字符串数组为空,或者有一个元素但是是空字符串,则返回空字符串
# 先排序
strs_list = sorted(strs)
if not strs or not strs[0]:
return ''
# # 先排序
# strs_list = sorted(strs)
# 前缀初始化为空字符串,然后循环递增
prefix = ''
for i in range(len(strs_list[0])):
prefix = strs_list[0][:i + 1]
# 判断排序后的字符串数组首尾是否有公共前缀,all判断比and快
# if all([strs_list[0].startswith(prefix), strs_list[-1].startswith(prefix)]):
if strs_list[0].startswith(prefix) and strs_list[-1].startswith(prefix):
continue
else:
# 不满足if,也就是prefix多加了一位的情况,对应最后一行的 return prefix[:-1]
break
else:
# 不是break结束循环,则执行这里
return prefix
return prefix[:-1]
如上实现,排序的时间复杂度是O(n)或者O(n log n),寻找子串的时间复杂度是O(n)级别,合在一起也就是O(n)或者O(n + n log n)
LeetCode专题-Python实现之第14题:Longest Common Prefix的更多相关文章
- Leetcode算法刷题:第14题 Longest Common Prefix
Longest Common Prefix 题目 给予一个列表,元素为字符串,写一个程序找出最长公共前缀 解题思路 先比较两个字符串,如果第一个字符不一样,则返回空值,比较完成后,用这个公共字符串和下 ...
- leetcode第14题--Longest Common Prefix
Problems:Write a function to find the longest common prefix string amongst an array of strings. 就是返回 ...
- LeetCode专题-Python实现之第13题:Roman to Integer
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第28题: Implement strStr()
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第27题:Remove Element
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第21题:Merge Two Sorted Lists
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第20题:Valid Parentheses
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第9题:Palindrome Number
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
随机推荐
- UWB DWM1000 跟随小车原理---一张图演示
更多内容参考论坛:bphero.com.cn
- vue自定义键盘事件
//自定义全局按键修饰符 Vue.config.keyCodes.f2 = 13;//enter为13此时F2==ENTER 调用;@keyup.f2='addData()'
- [POJ2823]Sliding Window 滑动窗口(单调队列)
题意 刚学单调队列的时候做过 现在重新做一次 一个很经典的题目 现在有一堆数字共N个数字(N<=10^6),以及一个大小为k的窗口.现在这个从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗 ...
- go-mod 入门
Q群有人问go mod 问题,自己也忘了些.顺便再整理下. GO111MODULE可以设置为三个字符串值之一:off,on或auto(默认值). off 则go命令从不使用新模块支持.它查找vendo ...
- H5 _拖放使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- day03笔记
1.list操作stus = ['xiaohei','xiaobai','xiaohuang','cxdser'] #数组.list.array#增加stus.append('原宝')#在list末尾 ...
- 如何在mysql客户端即mysql提示符下执行操作系统命令
环境描述: mysql版本:5.5.57-log 操作系统版本:Red Hat Enterprise Linux Server release 6.6 (Santiago) 需求描述: 在mysql的 ...
- easyui-combotree选中指定的值
选中根节点: //station_id为combotree控件id var station = $('#station_id').combotree('tree').tree('getRoots'); ...
- 将本地jar包打包到本地仓库和上传到私服
1.本地jar打包到本地仓库 mvn install:install-file -Dfile=jar包完整地址或相对地址 -DgroupId=自定义的groupID -DartifactId=自定义的 ...
- victory-native的使用
Victory用于构建交互数据可视化的可组合React组件的生态系统 想写又不想写,真尴尬...