Atcoder Mismatched Parentheses(栈)

You are given a string S of length N consisting of lowercase English letters and the characters .
Print the string S after performing the following operation as many times as possible.

  • Choose and delete a contiguous substring of S that starts with (, ends with ), and does not contain ( or ) other than the first and last characters.

It can be proved that the string S after performing the operation as many times as possible is uniquely determined without depending on how it is performed.

Constraints

  • 1≤N≤2×105
  • N is an integer.
  • S is a string of length N consisting of lowercase English letters and the characters .

Input

The input is given from Standard Input in the following format:

N
S

Output

Print the answer.


Sample Input 1 

8
a(b(d))c

Sample Output 1 

ac

Here is one possible procedure, after which S will be ac.

  • Delete the substring (d) formed by the fourth to sixth characters of S, making it a(b)c.
  • Delete the substring (b) formed by the second to fourth characters of S, making it ac.
  • The operation can no longer be performed.

Sample Input 2 

5
a(b)(

Sample Output 2 

a(

Sample Input 3 

2
()

Sample Output 3 

The string S after the procedure may be empty.


Sample Input 4 

6
)))(((

Sample Output 4 

)))(((

超时的代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
	int n;
	cin>>n;
	string s;
	cin>>s;
	int l=-1,r=-1;
	for(int i=0;i<s.size();i++)
	{
		if(s[i]=='(')
		l=i;
		if(l!=-1&&s[i]==')')
		{
			r=i;
			s.erase(s.begin()+l,s.begin()+r+1);
			l=-1;r=-1;
			i=-1;
			continue;
		}
	}
	cout<<s<<endl;
	return 0;
}
 

利用栈优化后的代码 ,这样就不需要每次都回到初始位置来找最里面的括号

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
	int n;
	cin>>n;
	string s;
	cin>>s;
	int l=-1,r=-1;
	stack<int> st;
	for(int i=0;i<s.size();i++)
	{
		if(s[i]=='(')
		st.push(i);
		if(!st.empty()&&s[i]==')')
		{
			r=i;
			l=st.top();
			st.pop();
			s.erase(s.begin()+l,s.begin()+r+1);
			l=-1;r=-1;
			if(st.empty())
			i=-1;
			else
			{
				i=st.top();
			}
			continue;
		}
	}
	cout<<s<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值