LeetCode 题解工作台

最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 "" 。 示例 1: 输入: strs = ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: strs = ["dog","racecar","car"] 输出: "" 解释:…

category

3

题型

code_blocks

11

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们以第一个字符串 为基准,依次比较后面的字符串的第 个字符是否与 的第 个字符相同,如果相同则继续比较下一个字符,否则返回 的前 个字符。 遍历结束,说明所有字符串的前 个字符都相同,返回 即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

 

示例 1:

输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

 

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 如果非空,则仅由小写英文字母组成
lightbulb

解题思路

方法一:字符比较

我们以第一个字符串 strs[0]strs[0] 为基准,依次比较后面的字符串的第 ii 个字符是否与 strs[0]strs[0] 的第 ii 个字符相同,如果相同则继续比较下一个字符,否则返回 strs[0]strs[0] 的前 ii 个字符。

遍历结束,说明所有字符串的前 ii 个字符都相同,返回 strs[0]strs[0] 即可。

时间复杂度 (n×m)(n \times m),其中 nnmm 分别为字符串数组的长度以及字符串的最小长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        for i in range(len(strs[0])):
            for s in strs[1:]:
                if len(s) <= i or s[i] != strs[0][i]:
                    return s[:i]
        return strs[0]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you understand how to handle edge cases like when there is no common prefix?

  • question_mark

    Can you describe the trade-offs between vertical scanning and horizontal scanning?

  • question_mark

    Will you be able to choose the most efficient approach based on the input size?

warning

常见陷阱

外企场景
  • error

    Failing to handle the case where no common prefix exists, returning an empty string instead of a valid result.

  • error

    Not accounting for the possibility of empty strings in the input, which can break certain approaches if not handled carefully.

  • error

    Incorrectly assuming that all strings must have a non-zero length; the edge case where an input array has an empty string should be checked.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    How would you optimize the solution for very large input sizes, say up to a million strings?

  • arrow_right_alt

    Can you modify the solution to find the longest common suffix instead of the prefix?

  • arrow_right_alt

    How would the problem change if strings could contain uppercase letters or other characters?

help

常见问题

外企场景

最长公共前缀题解:数组·string | LeetCode #14 简单