优选算法_栈_删除字符中的所有相邻重复项_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;
    }
};
相关推荐
傻啦嘿哟5 小时前
某招聘平台爬虫:爬取招聘岗位数据,分析各城市薪资水平
开发语言·爬虫·python
2501_933670795 小时前
2026秋招量化分析岗技能栈:Python、SQL、统计建模、回测项目怎么准备
开发语言·python·sql
2601_962077605 小时前
python Dejavu库快速识别音频指纹实例探究
python·音乐识别·dejavu库·音频指纹识别·实例探究
Dola_Zou5 小时前
工厂智能排产软件算法保护与按产线计费实战
算法·自动化·软件工程·软件加密
科技苑5 小时前
如何用Python编程实现一个简单的Web爬虫?
人工智能·python
李少兄6 小时前
JavaScript 数据类型完全指南
开发语言·javascript·ecmascript
码匠许师傅6 小时前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
dayDayupbetter6 小时前
Visual C++ 2010安装与使用高手秘籍
python
隐擎fox6 小时前
深入理解网络传输层安全:TLS 指纹识别(JA3/JA4)原理与 Python 协议层检测实战
爬虫·python·网络协议·安全·网络安全·https
医疗信息化王工6 小时前
DataForge:基于 Python 的数据库批量导出 Excel 工具——从架构到部署的全流程实战
数据库·python·excel