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

写完代码多思考怎么优化

相关推荐
h_a_o777oah7 小时前
2026 蓝桥杯软件 C++B组 国赛比赛经历及备赛建议
c++·经验分享·算法·蓝桥杯
lightqjx7 小时前
【算法】数据结构_并查集
数据结构·算法·并查集
小雨下雨的雨7 小时前
鸿蒙PC Electron框架实现流体气泡模拟器
前端·人工智能·算法·华为·electron·鸿蒙
txzrxz7 小时前
广度优先搜索详解(BFS)
算法·宽度优先
8Qi88 小时前
LeetCode 198:打家劫舍(House Robber)—— 题解 ✅
算法·leetcode·动态规划
无限码力8 小时前
华为非AI方向0603笔试真题-爆破小游戏(详细思路+多语言题解)
算法·华为·华为笔试真题·华为非ai笔试真题
wunaiqiezixin8 小时前
扫描线算法
算法
落羽的落羽8 小时前
【项目】JsonRpc框架——功能测试、项目总结
linux·服务器·开发语言·c++·qt·算法·机器学习
无限码力8 小时前
华为非AI方向笔试真题-昇腾NPU协同调度系统(详细思路+多语言题解)
算法·华为·华为机试·华为笔试真题·华为非ai笔试真题
小蒋学算法8 小时前
算法-掉落的方块-线段树
数据结构·算法