Files
leetcode-master/problems/1047.删除字符串中的所有相邻重复项.md
youngyangyang04 0e1f22bda2 Update
2020-07-19 16:32:49 +08:00

833 B

题目地址

https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/

思路

这道题目就像是我们玩过的游戏对对碰, 可以把字符串放到与一个栈中,然后如果相同的话 栈就弹出,这样最后栈里剩下的元素都是相邻不相同的元素了

C++代码

class Solution {
public:
    string removeDuplicates(string S) {
        stack<char> st;
        for (char s : S) {
            if (st.empty() || s != st.top()) {
                st.push(s);
            } else {
                st.pop();
            }
        }
        string result = "";
        while(!st.empty()) {
            result += st.top();
            st.pop();
        }
        reverse(result.begin(), result.end()); // 此时字符串需要反转一下
        return result;

    }
};