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

写完代码多思考怎么优化

相关推荐
木井巳8 分钟前
【动态规划: 路径问题】不同路径
java·算法·leetcode·动态规划
CQU_JIAKE19 分钟前
10.25【A】
数据结构·算法
greencherry_37 分钟前
大连模屿石膏课模具配比全固定,调色浇注之外还缺什么?
算法·生活
晒太羊的猫1 小时前
hot100子串
java·算法·leetcode
小豆庄2 小时前
视频脱敏引擎的追踪难题:转场误判定、ID撞号和淡入窗口
qt·算法·目标检测·音视频·视频·敏捷流程
海清河晏1112 小时前
加油站问题
数据结构·算法·leetcode
GG.WinGel2 小时前
质数数目(蓝桥杯练习题)
java·数据结构·算法·青少年编程·蓝桥杯
艾iYYY2 小时前
进程的状态
算法
秋天的怀念_David2 小时前
算法一千零一夜 · 第十七夜 长街点灯
java·程序人生·算法
CV爱数码2 小时前
论文精读|RED-CNN:残差编解码网络,低剂量 CT 去噪的经典基线
网络·人工智能·算法·cnn·ct·重建·x-ray