537 字
3 分钟
最长公共前缀问题

题目:#

Write a function to find the longest common prefix string amongst an array of strings.#

If there is no common prefix, return an empty string "".#

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:#

1 <= strs.length <= 200

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

strs[i] consists of only lowercase English letters if it is non-empty.

个人题解:#

本题要求的是在给定的 vector<string> 一个最长的公共前缀

我们可以直接拿 strs[0] 作为这个sub_prefix,所以之后的操作就是取反——即将不是公共的串进行截断,最终得到的结果就是真正的最长公共子串

所以,我们应该对题目给定的 strs 进行遍历

在得到 strs[i] 之后,对这个字符串进行遍历,以 std::string::find 函数来进行查找子前缀的操作,当发现不存在这样的子串的时候,用 std::string::substr 进行截断

在这题中,会用到 std::string::findstd::string::substr 方法(下为函数签名):

size_t find(const std::string& str, size_t pos = 0) const noexcept;

其第一个参数代表要查找的目标子字符串,而第二个参数代表从源字符串的哪个地方开始(默认为0,也就是源字符串的开头)

当它找到了这样的子字符串的时候,将会返回这个子字符串出现的索引,否则,会返回 std::string::npos

std::string substr(size_t pos = 0, size_t count = std::string::npos) const;

其第一个参数代表从哪个位置开始截断子串,count则是指这个字串的长度

它的返回值,就是截断的那个字符串

例如:

std::string s = "Hello world";
s = s.substr(0, 2);

在执行上述代码后,s 应该是 “He”

了解这些之后,我们便有如下代码:

// @lc code=start
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix = strs[0]; // 储存这个最长公共前缀的变量
for (size_t i = 1; i < strs.size(); i ++ ) {
// 检查目前得到的prefix是不是这个strs[i]的前缀
while (strs[i].find(prefix) != 0) {
// 如果不是,进行截断处理,将prefix变短
prefix = prefix.substr(0, prefix.length() - 1);
// 如果prefix被截断成空的了,直接返回空字符串
if (prefix.empty()) {
return "";
}
}
}
return prefix;
}
};
最长公共前缀问题
https://github.com/posts/最长公共前缀问题/
作者
FZSGBall
发布于
2025-10-21
许可协议
CC BY-NC-SA 4.0