优选算法_栈_删除字符中的所有相邻重复项_C++

一.题目解析

这就很象我们玩过的消消乐游戏,我们来模拟一下:

这就很象我们的栈数据结构

数据结构栈就不再过多描述

代码编写:stack()容器

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st; 
        
        for (char ch : s) {  // 遍历每个字符
            // 如果栈不为空 且 栈顶 == 当前字符 → 重复,弹出
            if (!st.empty() && st.top() == ch) {
                st.pop();
            } else {
                st.push(ch);  // 不重复就入栈
            }
        }
        
        // 把栈里的字符拼成结果
        string ret;
        while (!st.empty()) {
            ret += st.top();
            st.pop();
        }
        
        reverse(ret.begin(), ret.end());  // 反转得到正确顺序
        return ret;
    }
};

我们其实可以用数组模拟栈结构

代码编写:string模拟栈结构

cpp 复制代码
#include<bits/stdc++.h>
class Solution {
public:
    string removeDuplicates(string s) {
        string ret;
        for(auto ch:s)
        {
            if(!ret.empty()&&ch==ret.back())ret.pop_back();
            else ret+=ch;
        }
        return ret;
    }
};
相关推荐
forest_0911 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
九英里路12 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
吴可可12312 小时前
WScript Shell操作注册表详解
开发语言
纪念 22912 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
databook15 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
文丑颜不良啊15 小时前
LeetCode2761~2780题目解析
java·leetcode
师夷长技以自愈15 小时前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
jyOverQ15 小时前
从零学 JVM(六):垃圾回收算法详解——标记清除、标记复制与标记整理
jvm·算法
aifannihao16 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
码农小河6617 小时前
基于PHP的电商后台蜜罐系统
开发语言·php