代码随想录 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;
    }
};

写完代码多思考怎么优化

相关推荐
papaofdoudou15 分钟前
初中数学-整数整除判定法全解:从 2 到 19 的方法、依据与证明
算法
让学习成为一种生活方式25 分钟前
啤酒花基因组与重测序--Nature Communications
人工智能·算法
l1t43 分钟前
DeepSeek总结的OpenZL压缩变换器
c++·算法
想吃火锅100543 分钟前
【leetcode】238.除了自身以外数组的乘积js
javascript·算法·leetcode
坤坤子吖1 小时前
算法学习——高精度加减乘除
c++·笔记·学习·算法
CQU_JIAKE1 小时前
10.1[A]2267,磐久UMX【上下文128K,KVCache部分]
算法
朝朝辞暮i1 小时前
C++ 第 14 课:引用 &
开发语言·c++·算法
Joe_Wang52 小时前
【从0到1学习JVM · 21】既不浪费空间又没有碎片,标记整理算法到底慢在哪
jvm·学习·算法·垃圾回收·标记整理算法
让学习成为一种生活方式2 小时前
PlantCellChat--单细胞与空间转录组数据预测植物细胞间通讯的R包--The Plant Journal
算法
C++ 老炮儿的技术栈2 小时前
有符号变量与无符号变量的区别
服务器·开发语言·前端·数据结构·c++·算法·c