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

写完代码多思考怎么优化

相关推荐
晴天的雨.99221 分钟前
[C++算法]快乐数
数据结构·c++·算法
孤狼warrior25 分钟前
SCTR 五次失败的安全 BN 路由器
人工智能·python·深度学习·算法·安全·yolo
影视飓风TIM27 分钟前
C++11 核心新特性完整梳理
数据结构·c++·算法
晴天的雨.99228 分钟前
[C++]算法双指针 复写0
数据结构·c++·算法
橘子汽水16843 分钟前
Leetcode 128,49最长连续序列,字母异位词分组
java·算法·leetcode
mmmmath_31 小时前
LeetCode.438.找到字符串中所有字母异位词
数据结构·算法·leetcode
Nil2081 小时前
leetcode 22括号生成
算法·leetcode·深度优先
Navigator_Z1 小时前
LeetCode //C - 1237. Find Positive Integer Solution for a Given Equation
c语言·算法·leetcode