編寫一個函數(shù)來查找字符串數(shù)組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 ""
所有輸入只包含小寫字母 a-z
1、
class Solution(object):
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 strs[0][i] != string[i]:
return strs[0][:i]
# 特殊情況[""]有一個為空元素
return strs[0]
2、利用集合去重的原理
class Solution(object):
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