优选算法_栈_删除字符中的所有相邻重复项_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;
    }
};
相关推荐
xywww16811 小时前
大模型 API 选型实战:GPT、Gemini、Claude 接入时该看哪些指标?
运维·服务器·人工智能·python·gpt·langchain
王老师青少年编程15 小时前
2025年【江苏“信息与未来”编程思维】真题及题解(T2:坐标变换)
c++·题解·真题·坐标变换·编程思维·江苏·信息与未来
夜雪一千15 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
CS创新实验室16 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
能有时光16 小时前
PyTorch KernelAgent 源码解读 ---(4)--- ExtractorAgent
人工智能·pytorch·python
_Jimmy_16 小时前
Python 协程库如何使用以及有哪些使用场景
python
aqi0017 小时前
15天学会AI应用开发(十七)使用LangGraph实现会话记忆功能
人工智能·python·大模型·ai编程·ai应用
西门吹-禅17 小时前
java springboot N+1问题
java·开发语言·spring boot
第一程序员17 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
skywalk816317 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程