LeetCode 题解工作台
最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 "" 。 示例 1: 输入: strs = ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: strs = ["dog","racecar","car"] 输出: "" 解释:…
3
题型
11
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们以第一个字符串 为基准,依次比较后面的字符串的第 个字符是否与 的第 个字符相同,如果相同则继续比较下一个字符,否则返回 的前 个字符。 遍历结束,说明所有字符串的前 个字符都相同,返回 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]如果非空,则仅由小写英文字母组成
解题思路
方法一:字符比较
我们以第一个字符串 为基准,依次比较后面的字符串的第 个字符是否与 的第 个字符相同,如果相同则继续比较下一个字符,否则返回 的前 个字符。
遍历结束,说明所有字符串的前 个字符都相同,返回 即可。
时间复杂度 ,其中 和 分别为字符串数组的长度以及字符串的最小长度。空间复杂度 。
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]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?