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
相关推荐
lifloveyou4 小时前
table接口结构
python
8Qi84 小时前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
888CC++6 小时前
如何在 C 语言中进行程序调试?
前端·javascript·算法
Warson_L6 小时前
class 扩展
python
前端与小赵7 小时前
Python 数据结构陷阱与复数运算优化:列表、元组、字典成员操作辨析及 NumPy 高效实践
python
天天进步20157 小时前
Python全栈项目--基于深度学习的视频目标跟踪系统
python·深度学习·音视频
天天进步20157 小时前
Python全栈项目--Python自动化运维工具开发
运维·python·自动化
(●—●)橘子……7 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
爱吃羊的老虎8 小时前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python