跳转至

2023-05-06 删除字符串中的所有相邻重复项

力扣题目:Link

动图

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;
    }
};

感受

学完罗素哥的数据结构课之后再来练习算法题,嗯,感觉都看得懂了。

Magic!