14.最长公共前缀(LeetCode)

原题链接

14.最长公共前缀

菜狗本菜原思路

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
int len=strs.size();//求出动态数组的元素个数,不能用sizeof(strs),否则求的实际上是指针大小,是一个常量
int max=strs[0].length();//用length函数求出每个字符串数组所含元素个数
for (int i=0;i<len;i++){
    if (strs[i].length()<max)
    max=strs[i].length();
    //max的值为字符串数组中最短的字符串
}
for (int i=0;i<len;i++){
for (int j=i+1;j<len;j++){
    string s=strs[i].substr(0,max);
    if (s!=strs[j].substr(0,max)){
        max--;
        j--;
    }
    if (max==0)
    break;
}
 if (max==0)
    break;
}
return strs[0].substr(0,max);
    }
};

优化后的代码

class Solution {
public:
    string longestCommonPrefix(vector<string>& 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)。使用的额外空间复杂度为常数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Grausam

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值