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

写完代码多思考怎么优化

相关推荐
HaiLang_IT9 分钟前
【目标检测】基于卷积神经网络的轨道部件(扣件、轨枕、钢轨)缺陷检测算法研究
算法·目标检测·cnn
草莓熊Lotso9 分钟前
《算法闯关指南:优选算法--前缀和》--31.连续数组,32.矩阵区域和
c++·线性代数·算法·矩阵
csuzhucong11 分钟前
斜转魔方、斜转扭曲魔方
前端·c++·算法
C语言不精40 分钟前
c语言-优雅的多级菜单设计与实现
c语言·开发语言·算法
AI科技星1 小时前
张祥前统一场论:引力场与磁矢势的关联,反引力场生成及拉格朗日点解析(网友问题解答)
开发语言·数据结构·经验分享·线性代数·算法
C雨后彩虹1 小时前
最少交换次数
java·数据结构·算法·华为·面试
foxsen_xia1 小时前
go(基础01)——协程
开发语言·算法·golang
稚辉君.MCA_P8_Java1 小时前
Gemini永久会员 Go 返回最长有效子串长度
数据结构·后端·算法·golang
jyyyx的算法博客1 小时前
LeetCode 面试题 16.22. 兰顿蚂蚁
算法·leetcode
TL滕1 小时前
从0开始学算法——第五天(初级排序算法)
数据结构·笔记·学习·算法·排序算法