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

写完代码多思考怎么优化

相关推荐
郝学胜-神的一滴2 小时前
Effective STL 条款 17:用 swap 技巧去掉多余容量
c语言·开发语言·数据结构·c++·算法·rpc
玩转单片机与嵌入式2 小时前
深入浅出TinyML 36:如何验证一个TinyML系统真正具备工程应用价值?
网络·人工智能·算法
Nazarick4 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴4 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴4 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_116 小时前
算法札记:有限差分
算法
忙里偷闲学python6 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农6 小时前
11.21程序设计
数据结构·算法
Tisfy7 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6177 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法