Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string
""
.Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters
a-z
.
假设结果字符串就是第一个字符串,然后遍历后面的字符串,和第二个字符串逐个字符比较,相同的前缀作为结果字符串,然后和第三个字符串比较……
class Solution:
def longestCommonPrefix(self, strs):
res = strs[0]
ans = ''
for i in range(1, len(strs)):
j = 0
while strs[i][j] == res[j] and j < min(len(res), len(strs[i])):
j += 1
ans = res[:j]
return ans
j 加 1 以后超出字符串下表最大值运行提示字符串下表溢出
# 只要有一个字符串的字符不相等剩下的字符串相等也无效
# 因此只需要和最长的字符串进行比较就能知道整个字符串列表的最长公共前缀
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
#利用python的zip函数,把str看成list然后把输入看成二维数组
#左对齐纵向压缩,然后把每项利用集合去重
#之后遍历list中找到元素长度大于1之前的就是公共前缀
def longestCommonPrefix(self, strs):
if not strs:
return ""
ss = list(map(set, zip(*strs)))
res = ""
for i, x in enumerate(ss):
x = list(x)
if len(x) > 1:
break
res = res + x[0]
return res
class Solution:
def longestCommonPrefix(self, strs):
if not strs:
return ''
shortest = min(strs, key=len)
longest = max(strs, key=len)
for i, ch in enumerate(shortest):
if ch != longest[i]:
return shortest[:i]
return shortest
max()
函数、min()
函数的使用,第二个key
参数的设置python奇技淫巧——max/min函数的用法
enumerate()
函数的使用,同时列出数据和下标>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
zip()
函数的使用strs = ["flower","flow","flight", "abandon"]
for i in zip(*strs):
print(i)
输出:
('f', 'f', 'f', 'a')
('l', 'l', 'l', 'b')
('o', 'o', 'i', 'a')
('w', 'w', 'g', 'n')
map()
函数map(function, iterable, ...)
>>>def square(x) : # 计算平方数
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]