14. Longest Common Prefix [easy] (Python)
来源:互联网 发布:流体 热能 仿真软件 编辑:程序博客网 时间:2024/06/05 11:27
题目链接
https://leetcode.com/problems/longest-common-prefix/
题目原文
Write a function to find the longest common prefix string amongst an array of strings.
题目翻译
写个函数,找出一个字符串数组中所有字符串的最长公共前缀。
题目描述不清晰。。。补充几个例子,比如:
- {“a”,”a”,”b”} 返回 “” ,因为三个字符串没有公共前缀;
- {“a”, “a”} 返回 “a” 因为它是两个字符串的公共前缀;
- {“abca”, “abc”} 返回 “abc”;
- {“ac”, “ac”, “a”, “a”} 返回 “a”。
思路方法
思路一
很直观的思路,从任意一个字符串开始,扫描该字符串,依次检查其他字符串的同一位置是否是一样的字符,当遇到不一样时则返回当前得到的前缀。
代码
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' res = '' for i in xrange(len(strs[0])): for j in xrange(1, len(strs)): if i >= len(strs[j]) or strs[j][i] != strs[0][i]: return res res += strs[0][i] return res
思路二
先将给的字符串数组排序,然后只需要比较第一个和最后一个的公共前缀即可。虽然看起来比前面简单了很多,但实际上排序的代价并不低。
代码
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' strs.sort() res = '' for i in xrange(len(strs[0])): if i >= len(strs[-1]) or strs[-1][i] != strs[0][i]: return res res += strs[0][i] return res
思路三
用Python的zip()函数,可以实现比较精简的代码,不过效率不高。
代码
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' for i, chars in enumerate(zip(*strs)): if len(set(chars)) > 1: return strs[0][:i] return min(strs)
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51706442
0 0
- 14. Longest Common Prefix [easy] (Python)
- 14. Longest Common Prefix Easy
- Leetcode 14.Longest Common Prefix——python (easy)
- Easy-题目52:14. Longest Common Prefix
- Leetcode 14. Longest Common Prefix (Easy) (cpp)
- LeetCode 14. Longest Common Prefix (easy)
- 14. Longest Common Prefix-python
- Leetcode[Easy] - Longest Common Prefix
- [LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
- [leetcode:python]14.Longest Common Prefix
- Leet Code OJ 14. Longest Common Prefix [Difficulty: Easy]
- 14.LeetCode Longest Common Prefix(easy)[字符串公共前缀]
- 【LeetCode】14.Longest Common Prefix(Easy)解题报告
- 14. Longest Common Prefix
- 14.Longest Common Prefix
- 14. Longest Common Prefix
- 14. Longest Common Prefix
- 14. Longest Common Prefix
- 剑指offer(36)-平衡二叉树
- 自定义控件起步(一)(简单的自定义view)
- Python学习笔记(While循环)
- Android 线性布局
- ZOJ 3605 Find the Marble
- 14. Longest Common Prefix [easy] (Python)
- 一元云购CMS微信分享打不开解决办法
- POJ 3687 Labeling Balls-拓扑排序
- 迭代即为递归
- 进制转换 HDU2031
- PHP中级程序员常见面试题
- CubieTruck Plus linaro Desktop安装Tight VNC server RDP服务器
- eclipse开发project上显示有问号的愿意与解决方法
- linux安装rpm包时遇到Failed dependencies