优选算法_栈_删除字符中的所有相邻重复项_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;
    }
};
相关推荐
Aaron - Wistron28 分钟前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境39 分钟前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境1 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
lpfasd1231 小时前
MediaCrawler 项目深度分析
chrome·python·chrome devtools
Dxy12393102161 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
bamb002 小时前
一个项目带你入门AI应用开发01
python
0566462 小时前
Python康复训练——常用标准库
开发语言·python·学习
骊城英雄2 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#
圣保罗的大教堂2 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
吾儿良辰2 小时前
一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
开发语言·windows·c#