编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs == []:
return ""
# 初始最长公共前缀为数组中第一个元素
result = strs[0]
for i in range(1, len(strs)):
tmp = strs[i]
if len(result) > len(tmp):
result = result[0: len(tmp) + 1]
# 更新公共前缀
while(result != tmp[0: len(result)] and result):
result = result[0: -1]
return result
时间复杂度为O(mn), 空间复杂度为O(1)