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

写完代码多思考怎么优化

相关推荐
原凉是这样的丶11 分钟前
Qwen3.8-27B 开源后,我用双 RTX 4090 跑通了:vLLM 0.27.1、128K 上下文与 MTP 实测
linux·算法
码农大叔的博客38 分钟前
golang示例:for九九乘法表
开发语言·算法·golang
手写码匠1 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 故障演练实战:用混沌工程主动“搞破坏“,让智能体系统越炸越稳
人工智能·深度学习·算法·aigc
叠层归一研究院1 小时前
如何用程序搭建一个 AGI 种子系统(三):生长如何对接物理与数学宇宙
人工智能·python·算法·机器学习·transformer·agi
show4332 小时前
2026小程序端AI智能优化技术实践:转文字后自动纠错+润色+分段算法分析
人工智能·算法·小程序
平生不晚2 小时前
在 SVG 体系里画一条任意的线
前端·算法
逆境不可逃3 小时前
LeetCode 双题:415. 字符串相加与 143. 重排链表
算法
2601_950760793 小时前
TNF-α:自身免疫疾病治疗的核心靶点与信号通路解析
人工智能·算法·蛋白
不会代码的小猴4 小时前
2. 了解Qt
开发语言·c++·笔记·qt·算法
比奇堡裤头村4 小时前
统计学习方法——支持向量机
算法·支持向量机·学习方法