fqy131314

删除字符串中的所有相邻重复项(代码随想录力扣刷题)

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

 

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string
 

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

posted on 2023-04-08 11:51  会飞的鱼-blog  阅读(15)  评论(0)    收藏  举报  来源

导航