删除字符串中的所有相邻重复项

力扣链接

实现方法

使用栈来实现记录前置字母(包括删除前和删除后,所以需要动态增删的容器);
基础思想很简单,代码如下:

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st;
        int len = s.size();
        for(int i = 0; i < len; i++){
            if(st.empty()||st.top()!=s[i])st.push(s[i]);
            else if(st.top() == s[i])st.pop();
        }
        stack<char> rst;
        while(!st.empty()){
            char x = st.top();
            st.pop();
            rst.push(x);
        }
        string ss;
        while(!rst.empty()){
            char x = rst.top();
            rst.pop();
            ss += x;
        }
        return ss;
    }
};
posted @ 2025-09-10 19:47  q_z_chen  阅读(5)  评论(0)    收藏  举报