给你一个大小为 n 的字符串数组 strs ,其中包含n个字符串 , 编写一个函数来查找字符串数组中的最长公共前缀,返回这个公共前缀。
思路
利用 Python 内置的 zip 函数每次纵向取所有字符串的第 i 个字符;
对这些字符 set 后,如果都相同,则加入前缀,否则退出循环,返回结果;
Python
class Solution:
def longestCommonPrefix(self , strs: List[str]) -> str:
ret = []
for it in zip(*strs):
if len(set(it)) == 1:
ret.append(it[0])
else:
break
return ''.join(ret)