代码随想录 Leetcode1047. 删除字符串中的所有相邻重复项

题目:


代码(首刷自解 2024年1月21日):

cpp 复制代码
class Solution {
public:
    string removeDuplicates(string s) {
        if (s.size() < 2) return s;
        stack<char> t;
        for (int i = 0; i < s.size(); ++i) {
            if (t.empty()) t.push(s[i]);
            else {
                if (s[i] == t.top()) {
                    t.pop();
                    continue;
                } else {
                    t.push(s[i]);
                }
            }
        }
        string res = "";
        while (!t.empty()) {
            res = t.top() + res;
            t.pop();
        }
        return res;
    }
};

时间复杂度高

代码(二刷看解析 2024年1月21日)

cpp 复制代码
class Solution {
public:
    string removeDuplicates(string s) {
        string res = "";
        for (auto it : s) {
            if (res.empty() || it != res.back()) {
                res.push_back(it);
            } else {
                res.pop_back();
            }
        } 
        return res;
    }
};

写完代码多思考怎么优化

相关推荐
HEJOO93 分钟前
Linux 设备驱动系列——使用全局工作队列
java·linux·算法
Code_Solitude16 分钟前
c语言:递归
java·c语言·算法
edtoplort1 小时前
OpenAI紧急叫停GPT-6.1 Astra训练,奥尔特曼为何踩刹车
人工智能·gpt·算法
蒜香可达鸭1 小时前
让视频生成流水线跑不崩:一个事件溯源的多 Agent 可靠执行框架
算法
小羊没烦恼!2 小时前
系统内部模块(子系统)之间的耦合以及模块(子系统)划分
java·开发语言·前端·数据库·算法·c#
Nebula_g2 小时前
JavaSE拓展:Arrays和Collections工具类
java·开发语言·算法·排序算法·工具类·javase·技术栈
菜鸟~noob2332 小时前
【电子战】 第22篇:误差椭圆与置信区间【含matlab代码】
开发语言·算法·matlab
weixin_307779132 小时前
C++代码实现MATLAB中的normalize函数功能
开发语言·c++·算法·matlab
不会就选b2 小时前
算法日常・每日刷题--<动态规划>11
算法
(Charon)2 小时前
【C++面试】手写String类:同时实现拷贝构造与移动构造
c++·算法