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 ita(b)c
. - Delete the substring
(b)
formed by the second to fourth characters of S, making itac
. - 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;
}