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

写完代码多思考怎么优化

相关推荐
土司大王1 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
大熊背2 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander2583 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
祖力553 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜3 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者3 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
_Narcissus_4 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.4 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks4 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路4 小时前
算法8.环形队列
算法