Q:
输入: ["flower","flow","flight"]
输出: "fl"
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = ''
for i in zip(*strs):
# 如果集合长度为1,说明对应字符相等,截取到长度不为1的那个字符之前为止
if len(set(i)) == 1:
res += i[0]
else:
break
return res
zip():将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
nums = ['flower', 'flow', 'flight']
for i in zip(*nums):
print(i)
'''
输出结果:
('f', 'f', 'f')
('l', 'l', 'l')
('o', 'o', 'i')
('w', 'w', 'g')
'''