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
相关推荐
老四啊laosi2 小时前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
2301_764441332 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI2 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
妙为3 小时前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
Billlly3 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives3 小时前
atcoder ABC 452 题解
数据结构·算法
chushiyunen3 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA3 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
feifeigo1233 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
baidu_huihui3 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip