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

写完代码多思考怎么优化

相关推荐
.道阻且长.42 分钟前
10.LeetCode算法习题讲解--滑动窗口--最大连续为一的个数
算法·leetcode·职场和发展
学习中.........1 小时前
Karpathy nanoGPT 教程到底讲了什么
人工智能·算法·语言模型
城管不管2 小时前
重生——第十次面试之开源中国一面挂
java·linux·开发语言·算法·面试·职场和发展·开源
地平线开发者3 小时前
征程6|YOLOv5x 在 Horizon 征程6 上的端到端部署实践(下)
算法·自动驾驶
speop3 小时前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展
艾为电子3 小时前
【应用方案】电视沉浸式音频升级: 电视音频 awinic“芯片 + 算法” 一体化解决方案
算法·音视频
大熊背3 小时前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
Scabbards_4 小时前
面试Leetcode - 算法合集
算法·leetcode·面试
chuan.bai4 小时前
Java RAG 实战附录:qwen3 与 bge-m3 模型切换指南
java·人工智能·算法
wuyk5554 小时前
7.AVL 树:第一个自平衡二叉搜索树
开发语言·stm32·单片机·算法