Files
leetcode-master/problems/1047.删除字符串中的所有相邻重复项.md
youngyangyang04 4a0d040b11 Update
2020-07-21 09:16:52 +08:00

1.1 KiB
Raw Blame History

题目地址

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;

    }
};

笔者在先后在腾讯和百度从事技术研发多年利用工作之余重刷leetcode本文 GitHubhttps://github.com/youngyangyang04/leetcode-master 已经收录欢迎starfork共同学习一起进步。