Skip to content

LeetCode #14:最长公共前缀

最近投了一些岗位,也中了一部分 online coding,所以跟老板说研究那边进度先放缓一点,让我有时间把算法捡起来准备做题。

因为面试的基本上是工程岗不是前端岗,所以语言换成了 Python。之后可能就不一定会有 TS 的题解了。题干也不复制粘贴了,给个链接大家自己去看。

这次是第 14 题,最长公共前缀

题目分析

我的想法是,最长前缀一定是小等于一个数组中长度最短的字符串的,因此可以先按字符串长度排序然后遍历最短字符串,遍历到哪就是哪。

题解

一定是有更简单的写法的,但是这个也能过

python
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        arr = sorted(strs, key=lambda x: len(x))
        shortest = arr[0]

        res = ""

        for i in shortest:
            tmp = res + i
            if len([x for x in arr[1:] if x.startswith(tmp)]) == len(arr) - 1:
                res = tmp
            else:
                break

        return res

页面历史

Powered by VitePress and Elysium UI.
This site uses Microsoft Clarity to see how you use our website. By using our site, you agree that we and Microsoft can collect and use this data.