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

写完代码多思考怎么优化

相关推荐
xie_pin_an10 分钟前
C 语言排序算法全解析:从原理到实战,附性能对比
c语言·算法·排序算法
CoovallyAIHub11 分钟前
SAM 真的开始「分割一切」,从图像到声音,Meta 开源 SAM Audio
深度学习·算法·计算机视觉
三斗米15 分钟前
从思维链到思维树:一步步解锁大语言模型的推理能力
算法
前端小L28 分钟前
贪心算法专题(二):波动中的智慧——只取极值「摆动序列」
数据结构·算法·贪心算法
aini_lovee28 分钟前
基于Jousselme距离改进D-S证据理论matlab实现
开发语言·算法·matlab
白兰地空瓶38 分钟前
你以为树只是画图?不——它是算法面试的“隐形主角”
前端·javascript·算法
好易学·数据结构1 小时前
可视化图解算法74:最小花费爬楼梯
数据结构·算法·leetcode·动态规划·力扣
Maỿbe1 小时前
力扣hot图论部分
算法·leetcode·图论
LYFlied1 小时前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌1 小时前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树