Skip to content

Files

Latest commit

May 16, 2025
d5281d5 · May 16, 2025

History

History
72 lines (48 loc) · 1.34 KB

0014-longest-common-prefix.adoc

File metadata and controls

72 lines (48 loc) · 1.34 KB

14. 最长公共前缀

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

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

示例 1:

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

示例 2:

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

提示:

  • 1 <= strs.length <= 200

  • 0 <= strs[i].length <= 200

  • strs[i] 仅由小写英文字母组成

思路分析

最简单的解题办法是逐列扫描。看题解,也不需要保存前缀,发现不同时,直接从字符串中截取即可。

{image_attr}
{image_attr}
{image_attr}
{image_attr}
一刷
link:{sourcedir}/_0014_LongestCommonPrefix.java[role=include]
二刷
link:{sourcedir}/_0014_LongestCommonPrefix_2.java[role=include]

参考资料

  1. 14. 最长公共前缀 - 官方题解 — 解法很多!