[LintCode 78] 最长公共前缀(Python)
来源:互联网 发布:海森矩阵的逆矩阵 编辑:程序博客网 时间:2024/06/11 09:36
思路描述
给k个字符串,求出他们的最长公共前缀(LCP)
样例
在 “ABCD” “ABEF” 和 “ACEF” 中, LCP 为 “A”
思路
- 法一:用python的zip函数解决
- 法二:两两比较
代码
class Solution: """ 法一:使用zip函数 @param: strs: A list of strings @return: The longest common prefix """ def longestCommonPrefix(self, strs): # write your code here if strs is None or len(strs) == 0: return '' for i in range(len(strs)): strs[i] = list(strs[i]) tmp = zip(*strs) res = '' for i in tmp: if len(set(i)) == 1: res += i[0] return res """ 两两比较 @param: strs: A list of strings @return: The longest common prefix """ def longestCommonPrefix1(self, strs): # write your code here if strs is None or len(strs) == 0: return '' res = strs[0] for i in range(1, len(strs)): tmp = res res = '' for j in range(min(len(strs[i]),len(tmp))): if tmp[j] == strs[i][j]: res += tmp[j] else: break return res
复杂度分析
时间复杂度
阅读全文
0 0
- [LintCode 78] 最长公共前缀(Python)
- lintcode-最长公共前缀-78
- LintCode 78 最长公共前缀
- [Lintcode] #78 最长公共前缀
- LintCode-最长公共前缀
- LintCode 最长公共前缀
- lintcode ---- 最长公共前缀
- LintCode : 最长公共前缀
- lintcode,最长公共前缀
- 最长公共前缀 -LintCode
- [Lintcode]最长公共前缀
- lintcode -- 最长公共前缀
- lintcode 最长公共前缀
- Lintcode(6)-最长公共前缀
- lintcode之最长公共前缀
- LintCode(M)最长公共前缀
- LintCode 78.最长公共前缀
- lintcode python ——最长公共前缀(LCP)
- .NET调用JAVA的WebService方法
- CentOS 7 安装xrdp 远程桌面
- 前端学习笔记之1 基础语法及标签
- Maven项目下update maven后Eclipse报错:java.lang.ClassNotFoundException
- Android Material Design学习之二AppBarLayout
- [LintCode 78] 最长公共前缀(Python)
- 创建型模式之原型模式
- 移动商城第四篇【Controller配置、添加品牌之文件上传和数据校验】
- Android中使用SVG
- 大数据处理之——简明Spark介绍
- iphone上实现1px的border
- TCPIP、Http、Socket的区别
- oracle的数据泵导入导出数据
- linux下如何实现mysql数据库每天自动备份定时备份