Leetcode 14.最长公共前缀

文章目录

题目

14.最长公共前缀

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

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

示例 1:

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

输出:"fl"

示例 2:

输入:strs = ["dog","racecar","car"]

输出:""

解释:输入不存在公共前缀。

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

思路

算法:
暴力枚举 O(mn)

  1. 暴力枚举方法很简单:先找到所有字符串的最短长度 m,然后从长度 1 到 m 依次枚举判断是否所有字符串的前缀是否都相等。
  2. 注意输入可能为空数组。

时间复杂度:最坏情况下,对于 n 个字符串,都需要遍历到最短长度,故总时间复杂度为 O(mn) .

空间复杂度:需要额外 O(m) 的空间存储答案。

代码

C++代码:

cpp 复制代码
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();

        if (n == 0)
            return "";

        size_t m = strs[0].length();

        for (int i = 1; i < n; i++)
            m = min(m, strs[i].length());

        for (int s = 1; s <= m; s++) {
            char c = strs[0][s - 1];
            for (int i = 1; i < n; i++)
                if (strs[i][s - 1] != c)
                    return strs[0].substr(0, s - 1);
        }

        return strs[0].substr(0, m);
    }
};

python3代码:

py 复制代码
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        res = ""
        for i in zip(*strs):
            if len(set(i)) != 1:
                return  res
            else:
                res += i[0]
        return res
相关推荐
DARLING Zero two♡21 小时前
接入 AI Ping 限免接口,让 GLM-4.7 与 MiniMax-M2.1 成为你的免费 C++ 审计专家
开发语言·c++·人工智能
不惑_21 小时前
通俗理解感知机(Perceptron)
人工智能·python
Everybody_up21 小时前
pycharm中编译环境配置
ide·python·pycharm
零小陈上(shouhou6668889)1 天前
YOLOv8+PyQt5输电线路缺陷检测(目前最全面的类别检测,可以从图像、视频和摄像头三种路径检测)
python·qt·yolo
luoluoal1 天前
基于python的爬虫的贵州菜价可视化系统(源码+文档)
python·mysql·django·毕业设计·源码
东东的脑洞1 天前
【面试突击】Redis 主从复制核心面试知识点
redis·面试·职场和发展
2501_921649491 天前
股票 API 对接,接入美国纳斯达克交易所(Nasdaq)实现缠论回测
开发语言·后端·python·websocket·金融
程序喵大人1 天前
constexpr
开发语言·c++·constexpr
Larry_Yanan1 天前
Qt多进程(五)QUdpSocket
开发语言·c++·qt·学习·ui
De-Alf1 天前
Megatron-LM学习笔记(6)Megatron Model Attention注意力与MLA
笔记·学习·算法·ai