删除字符串中的所有相邻重复项(代码随想录力扣刷题)
给出由小写字母组成的字符串 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;
}
};
浙公网安备 33010602011771号