
思路:
用栈来解决,在栈不为空的情况下,逐个取出字符然后和栈顶元素进行比较,如果相同则栈执行pop操作,然后取下一个字符串,如果不相等或者栈为空则执行push操作
#include<iostream>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
class Solution
{
public:
string removeDuplicates(string S)
{
stack<char> cStack;
string result = "";
for(int c=0; c<S.size(); )
{
while(!cStack.empty() && S[c] == cStack.top())
{
cStack.pop();
c++;
}
cStack.push(S[c]);
c++;
}
while(!cStack.empty())
{
result+=cStack.top();
cStack.pop();
}
reverse(result.begin(),result.end());
return result;
}
};
int main()
{
string str = "abbaca";
string result = "";
Solution s;
result = s.removeDuplicates(str);
cout<<result<<endl;
return 0;
}
更进一步:(膜拜大佬一波)
链接在此:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/comments/98920
还是用栈没错,但是这次用的是栈的思想,而不是直接使用stack
class Solution
{
public:
string removeDuplicates(string S)
{
int top = -1;
for(auto c:S)
{
if(top==-1)
{
S[++top] = c;
}
else
{
if(S[top] == c)
top--;
else
S[++top]=c;
}
}
return {S.begin(),S.begin()+top+1};
}
};
本文介绍了一种使用栈思想去除字符串中所有相邻重复字符的高效算法。通过两次遍历,首次利用栈或数组记录字符,第二次逆序拼接结果,实现简洁的解决方案。文章提供了两种实现方式,一种直接使用C++标准库中的栈,另一种则采用数组模拟栈操作。
1047. 删除字符串中的所有相邻重复项&spm=1001.2101.3001.5002&articleId=90743621&d=1&t=3&u=06e2291d57a94fe19f7aa9012dbf08ad)
664

被折叠的 条评论
为什么被折叠?



