编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
所有输入只包含小写字母 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