栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

14.最长公共前缀(LeetCode)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

14.最长公共前缀(LeetCode)

原题链接

14.最长公共前缀

菜狗本菜原思路
class Solution {
public:
    string longestCommonPrefix(vector& strs) {
int len=strs.size();//求出动态数组的元素个数,不能用sizeof(strs),否则求的实际上是指针大小,是一个常量
int max=strs[0].length();//用length函数求出每个字符串数组所含元素个数
for (int i=0;i 
优化后的代码 
class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        if (!strs.size()) {
            return "";
        }//像这种只剩空串的话直接返回就好
        string prefix = strs[0];
        int count = strs.size();
        for (int i = 1; i < count; ++i) {
            prefix = longestCommonPrefix(prefix, strs[i]);
            //依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。
            if (!prefix.size()) {
                break;
            }
        }
        return prefix;
    }
//重载函数牛逼
    string longestCommonPrefix(const string& str1, const string& str2) {
        int length = min(str1.size(), str2.size());
        int index = 0;
        while (index < length && str1[index] == str2[index]) {
            ++index;
        }
        return str1.substr(0, index);
    }
};
复杂度分析

时间复杂度:O(mn),其中 m 是字符串数组中的字符串的平均长度,n是字符串的数量。
空间复杂度:O(1)。使用的额外空间复杂度为常数。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/297493.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号