LeetCode刷题记录.Day26

删除字符串中所有相邻重复项

1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)

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

栈的应用题,主要考察能不能灵活应用栈的特点来解决字符匹配问题。个人读题的时候一时之间想不到这个方法,大概只能多做多练了

posted @ 2022-11-26 22:25  凱風快晴  阅读(11)  评论(0)    收藏  举报