[leetcode14]最长公共前缀

2023-10-09  本文已影响0人  欢仔_159a

题目:
编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

本人的最佳烂代码:

    def longestCommonPrefix(self, strs: List[str]) -> str:
        res = ""
        for temp in zip(*strs):
            temp = set(temp)
            if len(temp) == 1:
                res += temp.pop()
            else:
                break
        return res

反思:
1、zip()和zip(*)的使用,已经遇到多次,很重要
2、集合的用法、特定(无序、不重复,python3.11看起来是有序的)
3、集合元素的获取,只能使用for循环或者iter(),或者pop()

iter()和next()函数访问集合元素:

set1 = {1,2,3,4,5,6}
iterobj = iter(set1)
next(iterobj)
1
next(iterobj)
2

for循环遍历集合元素

for i in set1:
... print(i)
...
1
2
3
4
5
6

pop()访问,弹出相当于删除了。

set1.pop()
1

上一篇下一篇

猜你喜欢

热点阅读