思路:
用栈来实现,遍历s,如果当前元素与栈顶元素相同,则弹栈,否则入栈。
栈内剩下的元素全部弹栈,再翻转
代码方面:元素入栈的情况 if(mystack.empty() ||mystack.top() !=num)
元素出栈,用mystack.pop(),不要写成mystack.pop(num):
注意 用result接收mystack.top() 的元素,pop()仅弹出元素,通常与top配合使用
/*
* @lc app=leetcode.cn id=1047 lang=cpp
*
* [1047] 删除字符串中的所有相邻重复项
*/
// @lc code=start
class Solution {
public:
string removeDuplicates(string s) {
stack<char> mystack;
for(char num:s)
{
if(mystack.empty() || mystack.top() != num)
{
mystack.push(num);
}
else{
mystack.pop();
}
}
string result = "";
while(!mystack.empty())
{
result +=mystack.top();
mystack.pop();
}
reverse(result.begin(),result.end());
return result;
}
};
// @lc code=end