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

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> stack;

        for (int i = 0; i < s.size(); i ++) {
            if (stack.empty() || s[i] != stack.top()) stack.push(s[i]);
            else stack.pop();
        }

        string res = "";
        while (!stack.empty()) res += stack.top(), stack.pop();

        reverse(res.begin(), res.end());

        return res; 
    }
};
posted @ 2022-08-27 09:18  hjy94wo  阅读(20)  评论(0)    收藏  举报