leetcode--最长公共前缀--python
2019-04-28 14:31
337 查看
文章目录
题目
题目详情
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例
输入: ["flower","flow","flight"] 输出: "fl"
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
解题思路
- 只要取出最大的字符串和最小的字符串,那么就可以代表整组的字符串求最长公共前缀了。
- 再求出最长和最短字符串的最长前缀就可以了
代码
class Solution: def longestCommonPrefix(self, strs): if not strs: return "" s1 = min(strs) #最小 s2 = max(strs) #最大 for i,x in enumerate(s1): if x != s2[i]: #判断条件 return s2[:i] return s1
运行结果
最佳方案
32ms
class Solution: def longestCommonPrefix(self, strs: 'List[str]') -> 'str': if not strs: return'' if len(strs)==1: return strs[0] strs.sort() p='' for x,y in zip(strs[0],strs[-1]): if x==y: p+=x else: break return p
相关文章推荐
- python [LeetCode] 最长公共前缀
- LeetCode:最长公共前缀(Python版本)
- LeetCode14. python实现:最长公共前缀问题☆
- Python学习-Leetcode刷题记5:最长公共前缀
- [算法Rust,Go,Python,JS实现)]LeetCode之14-最长公共前缀
- LeetCode题解(python)-14. 最长公共前缀
- leetcode的python实现 刷题笔记14:最长公共前缀
- leetcode-腾讯精选练习(50 题)python #14最长公共前缀
- leetcode_14. 最长公共前缀(python)
- leetcode 14 最长公共前缀(python)
- LeetCode_Q14_最长公共前缀
- LeetCode | Longest Common Prefix(最长公共前缀)
- LeetCode 14. Longest Common Prefix(最长公共前缀)
- leetcode-14. Longest Common Prefix(寻找字符串数组最长公共前缀)
- python实现leetcode-第18题-最大公共前缀
- leetcode——Longest Common Prefix 最长公共前缀(AC)
- LeetCode 14. Longest Common Prefix(最长公共前缀)
- lintcode python ——最长公共前缀(LCP)
- Leetcode#14. Longest Common Prefix (最长公共前缀字符串)
- 每日一练之Longest Common Prefix【LeetCode No.14】——求字符串的最长公共前缀