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

写完代码多思考怎么优化

相关推荐
茜茜西西CeCe7 分钟前
数字图像处理-图像增强(2)
人工智能·算法·计算机视觉·matlab·数字图像处理·图像增强·陷波滤波器
薰衣草233332 分钟前
hot100练习-11
算法·leetcode
地平线开发者1 小时前
征程 6 | 工具链如何支持 Matmul/Conv 双 int16 输入量化?
人工智能·算法·自动驾驶
甄心爱学习1 小时前
数值计算-线性方程组的迭代解法
算法
stolentime1 小时前
SCP2025T2:P14254 分割(divide) 题解
算法·图论·组合计数·洛谷scp2025
Q741_1471 小时前
C++ 面试基础考点 模拟题 力扣 38. 外观数列 题解 每日一题
c++·算法·leetcode·面试·模拟
W_chuanqi2 小时前
RDEx:一种效果驱动的混合单目标优化器,自适应选择与融合多种算子与策略
人工智能·算法·机器学习·性能优化
L_09072 小时前
【Algorithm】二分查找算法
c++·算法·leetcode
靠近彗星2 小时前
3.3栈与队列的应用
数据结构·算法
Han.miracle6 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode