消除相邻的三个相同字符的解法1.使用栈 2.使用双端队列

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
#define PII pair<int,int>
#define x first
#define y second
int main()
{
	string s;
	cin >> s;
	deque<char> q;
	for( auto it : s )
	{
		if( q.size()>=2 && q.back() == it && q[q.size() - 2] == it)
		{
			q.pop_back();
			q.pop_back();
		}
		else
		{
			q.push_back(it);
		}
	}
	if(q.empty())
	{
		cout << "NAN" << endl;
	}
	else
	{
		for( auto it : q)
		{
			cout << it;
		}
	}
	return 0;
}

这是deque的做法,下面是栈的做法

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
#define PII pair<int,int>
#define x first
#define y second
//#define int long long 
using ll = long long ;
/*
//这个是我写错的,依托答辩-----------
int main()
{
	IOS;
	string s1,s2;
	cin >> s1;
	stack<char> st;
	char f , ff;
	int l = s1.size();
	if( l < 3)
	{
		cout << s1 << endl;
		return 0;
	}
	f = s1[0] , ff = s1[1];
	st.push(f) , st.push(ff);
	for( int i = 2 ; i < l ; i ++ )
	{
		if( s1[i] == ff && ff == f)
		{
			st.pop(),st.pop();
			//更新f 和 ff
			ff = st.top();
			st.pop();
			f = st.top();
			st.push(ff);
		}
		else
		{
			st.push(s1[i]);
			f = ff;
			ff = s1[i];
		}
	}
	while( ! st.empty() )
	{
		f = st.top();
		st.pop();
		s2 = f + s2;
	}
	cout << s2 << endl;
}
*/
int main()
{
	string s;
	cin >> s;
	stack<char> st;
	for( auto it : s )
	{
		if( st.size() >= 2 )
		{
			char x = st.top();
			st.pop();//先把x去掉
			if( x == it && it == st.top())//三个连续相等的
			{
				st.pop();
			}
			else
			{
				st.push(x),st.push(it);
			}
		}
		else
		{
			st.push(it);
		}
	}
	string s1;
	if( st.empty() )
	{
		cout << "NAN" << endl;
		return 0;
	}
	while(!st.empty())
	{
		s1 +=  st.top();
		st.pop();
	}
	reverse(s1.begin(),s1.end());
	cout << s1 << endl;
}

这里是栈的写法,上面注释掉的部分是存在bug的东西,嘿嘿嘿

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值