Files
leetcode-master/problems/1047.删除字符串中的所有相邻重复项.md
youngyangyang04 fd9e7a2d05 Update
2020-08-13 09:15:50 +08:00

1.5 KiB
Raw Blame History

题目地址

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

思路

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

如动画所示:

从栈中弹出剩余元素此时是字符串ac因为从栈里弹出的元素是倒叙的所以在对字符串进行反转一下就得到了最终的结果。

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(); // s == st.top()
            }
        }
        string result = "";
        while(!st.empty()) {
            result += st.top();
            st.pop();
        }
        reverse(result.begin(), result.end()); // 此时字符串需要反转一下
        return result;

    }
};

更过算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。