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
相关推荐
BirdenT1 天前
20260518紫题训练
c++·算法
databook1 天前
切线的魔法:用 SymPy 和 Manim 轻松搞定导数动画
python·数学·动效
程序员榴莲1 天前
Python 正则表达式入门:从匹配手机号到提取文本内容
python·正则表达式
程序员榴莲1 天前
Python 中的 @property:像访问属性一样调用方法
开发语言·前端·python
坐吃山猪1 天前
【Nanobot】README04_LEVEL2 提供商系统设计
python·源码·agent·nanobot
玛卡巴卡ldf1 天前
【LeetCode 手撕算法】(多维动态规划)不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离
java·数据结构·算法·leetcode·动态规划·力扣
坐吃山猪1 天前
【Nanobot】README09_LEVEL4 添加新聊天渠道
开发语言·网络·python·源码·nanobot
被AI抢饭碗的人1 天前
算法:数据结构
数据结构·算法
运筹vivo@1 天前
leetcode每日一题: 跳跃游戏 IV
leetcode·游戏·宽度优先
_深海凉_1 天前
LeetCode热题100-验证二叉搜索树
算法·leetcode·职场和发展