导航页-LeetCode专题-Python实现

相关代码已经上传到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的更多相关文章

  1. Leetcode算法刷题:第14题 Longest Common Prefix

    Longest Common Prefix 题目 给予一个列表,元素为字符串,写一个程序找出最长公共前缀 解题思路 先比较两个字符串,如果第一个字符不一样,则返回空值,比较完成后,用这个公共字符串和下 ...

  2. leetcode第14题--Longest Common Prefix

    Problems:Write a function to find the longest common prefix string amongst an array of strings. 就是返回 ...

  3. LeetCode专题-Python实现之第13题:Roman to Integer

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  4. LeetCode专题-Python实现之第28题: Implement strStr()

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  5. LeetCode专题-Python实现之第27题:Remove Element

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  6. LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  7. LeetCode专题-Python实现之第21题:Merge Two Sorted Lists

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  8. LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  9. LeetCode专题-Python实现之第9题:Palindrome Number

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

随机推荐

  1. JS for循环 if判断、white循环。小练习

    1----输入正整数n,求1-n的和. var n=prompt("请输入一个正整数"); var sum=0; for (var i=1;i<=n;i++) { sum=s ...

  2. Hive与Hbase整合

    Hive与Hbase整合 1.文档 Hive HBase Integration 2.拷贝jar文件 2.1.把Hbase的lib目录下面的jar文件全部拷贝到Hive的lib目录下面 cd /hom ...

  3. Android四大组件的简介

    Android开发四大组件分别是: 一.活动(Activity): 用于表现功能.二.服务(Service): 后台运行服务,不提供界面呈现. 三.广播接收器(BroadcastReceiver):用 ...

  4. angular.module()

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  5. Charles抓包软件简介

    Charles简介: Charles是一款抓包神器,因为他是基于 java 开发的,所以跨平台,Mac.Linux.Window下都是可以使用的,确保安装之前已经安装了JDK.Charles官网地址: ...

  6. Java使用BufferedImage修改图片内容

    1.修改图片的架包 <dependency> <groupId>commons-io</groupId> <artifactId>commons-io& ...

  7. easyui-combotree选中指定的值

    选中根节点: //station_id为combotree控件id var station = $('#station_id').combotree('tree').tree('getRoots'); ...

  8. String类,StringBuffer类转字符数组

    String不可变类型和StringBuffer可变类型 String类和StringBuffer类都是字符串表示类,区别在于String对象引用变量是不可变的,而StringBuffer类对象引用变 ...

  9. git命令别名(Alias)

    每次切换分支: git ckeckout branch_name 等命令费时又费力,git 别名配置起来: 别名配置: git config --global alias.ck ckeckout 其他 ...

  10. linux常见命令实践.

    ls -la : 给出当前目录下所有文件的一个长列表,包括以句点开头的“隐藏”文件 ls -a . .. 1 online_tools online_tools_0803 ll: 竖列显示所有文件 l ...