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

写完代码多思考怎么优化

相关推荐
晚霞的不甘3 小时前
Flutter for OpenHarmony 可视化教学:A* 寻路算法的交互式演示
人工智能·算法·flutter·架构·开源·音视频
望舒5133 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
C++ 老炮儿的技术栈3 小时前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
KYGALYX3 小时前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀3 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
踢足球09293 小时前
寒假打卡:2026-2-8
数据结构·算法
IT猿手4 小时前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风4 小时前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀4 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
晚霞的不甘4 小时前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频