优选算法_栈_删除字符中的所有相邻重复项_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;
    }
};
相关推荐
aqi0044 分钟前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn2 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
JieE21213 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵18 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent