Longest Common Prefix 最長公共前綴
題目
解法1、逐位比較
class Solution:
def longestCommonPrefix(self, strs):
if not strs:
return ""
for i in range(len(strs[0])):
for string in strs[1:]:
if i >= len(string) or string[i] != strs[0][i]:
return strs[0][:i]
return strs[0]# 當strs = [""]時,strs視爲存在,所以此處我們直接返回第一個元素,即“”
以第一個單詞作爲基準,不同就返回前i位
注意第二個單詞可能比第一個單詞短,防止超出循環範圍,先比較i >= len(string)
解法2、利用集合性質
class Solution:
def longestCommonPrefix(self, strs):
result = ""
i = 0
while True:
try:
sets = set(string[i] for string in strs)
if len(sets) == 1:
result += sets.pop()
i += 1
else:
break
except Exception as e:
break
return result
1、分別把所有單詞的對應位放入集合,若集合長度不爲1就返回
2、用while True時注意及時跳出,常藉助try except
解法3、zip+sets
class Solution:
def longestCommonPrefix(self, strs):
r = [len(set(c)) == 1 for c in zip(*strs)] + [0]
return strs[0][:r.index(0)] if strs else ''
1、zip(*)解壓,zip(*star)的結果(輸入:strs = [“flower”, “flow”, “flight”])
2、因爲在python中0==False,此處index(0)結果爲2
解法4、藉助os模塊自帶函數。。。
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
return os.path.commonprefix(strs)
出處
1、2、https://www.bilibili.com/video/av45842114
3、對應題目下Knife丶的題解