题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
解答
法1.取列表中每个单词同一位置的字母,看看该位置字母是否相等(用zip(*)来实现取同一位置字母,用set()的不重复元素集特性来判断字母们是否相等)
list(zip(*str1))
Out[24]: [('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')]
list(zip(str1))
Out[25]: [('flower',), ('flow',), ('flight',)]
执行用时 :60 ms, 在所有 Python3 提交中击败了35.67%的用户
内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.53%的用户
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
category = list(zip(*strs))
res = ""
for i in range(len(category)):
issame = set(category[i])
if len(issame) == 1:
res = res + list(issame)[0]
else:
break
## 这里一定要加break,不然可能会造成两单词中任意位置有字母相同,都会被返回。
## 我们要求的是从首字母开始相同才返回。
return res
法2.先将列表中单词排序,之后比较首位和末位的单词有多少相同字母。(他俩应该是相同位数最少的两组单词)
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
res = ""
strs.sort()
first = strs[0]
last = strs[-1]
for i in range(len(first)):
if first[i] == last[i] and i <= len(last):
res = res + first[i]
else:
break
return res
笔记
集合 set()
下面文章中讲的很详细了
https://www.cnblogs.com/yangliguo/p/7773968.html
https://www.runoob.com/python3/python3-set.html