码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode14. 最长公共前缀 🌟

时间:2019-06-30 12:36:39      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:==   http   解释   sel   item   返回   空字符串   示例   problems   

题目:

  编写一个函数来查找字符串数组中的最长公共前缀。

  如果不存在公共前缀,返回空字符串 ""。

示例 1:

  输入: ["flower","flow","flight"]
  输出: "fl"
示例 2:

  输入: ["dog","racecar","car"]
  输出: ""
  解释: 输入不存在公共前缀。
说明:

  所有输入只包含小写字母 a-z 。

来源:力扣(LeetCode)
解答:

leetcode优秀方案:

 1 class Solution:
 2     def longestCommonPrefix(self, strs: List[str]) -> str:
 3         if len(strs)==0:    return ""
 4         if len(strs)==1:    return strs[0]
 5         strs.sort()
 6         p=""
 7         for x,y in zip(strs[0],strs[-1]):
 8             if x==y:
 9                 p+=x
10             else:
11                 break
12         return p
 1 class Solution:
 2     def longestCommonPrefix(self, strs: List[str]) -> str:
 3         if len(strs)==0:
 4             return ‘‘
 5         s1=min(strs)
 6         s2=max(strs)
 7         for i,v in enumerate(s1):
 8             if v!=s2[i]:
 9                 return s1[:i]
10         return s1
1 class Solution:
2     def longestCommonPrefix(self, strs: List[str]) -> str:
3         res = ""
4         for i in zip(*strs):
5             if len(set(i)) == 1:
6                 res += i[0]
7             else:
8                 return res
9         return res
 1 class Solution:
 2     def longestCommonPrefix(self, strs: List[str]) -> str:
 3         if len(strs) < 1:
 4             return ""
 5         index = 1
 6         prefix = strs[0]
 7         while index < len(strs):
 8             while prefix != strs[index][: len(prefix)]:
 9                 prefix = prefix[:-1]
10                 if len(prefix) < 1:
11                     return ""
12             index += 1
13         return prefix

个人愚见:

 1 class Solution:
 2     def longestCommonPrefix(self, strs: List[str]) -> str:
 3         common = ‘‘
 4         min_length = min([len(i) for i in strs])  if strs else 0
 5         for i in range(0, min_length):
 6             letter = set()
 7             for item in strs:
 8                 letter.add(item[i])
 9             if len(letter) == 1:
10                 common += item[i]
11             else:
12                 return common
13         return common

 

leetcode14. 最长公共前缀 🌟

标签:==   http   解释   sel   item   返回   空字符串   示例   problems   

原文地址:https://www.cnblogs.com/catyuang/p/11109326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!