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
相关推荐
可靠的仙人掌4 分钟前
SAC(Soft Actor-Critic)算法底座
开发语言·算法·php
量化吞吐机17 分钟前
近期量化工具怎么选,先看规则流程能否承接
人工智能·python
一世繁华行31 分钟前
Python帧对象
python
王老师青少年编程41 分钟前
csp信奥赛C++高频考点专项训练:【二分答案】案例2:木材加工
c++·二分答案·csp·高频考点·信奥赛·木材加工
三川6981 小时前
Tkinter库的学习记录08- 容器控件
python
海石1 小时前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石1 小时前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
c_lb72881 小时前
近期AI量化工具选择,学习开发执行要分开
人工智能·python
天天进步20151 小时前
Python全栈项目--校园食堂点餐与推荐系统
开发语言·python
aaPIXa6221 小时前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++