Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.
To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed.
We remind that bracket sequence ss is called correct if:
- ss is empty;
- ss is equal to "(tt)", where tt is correct bracket sequence;
- ss is equal to t1t2t1t2, i.e. concatenation of t1t1 and t2t2, where t1t1 and t2t2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.
Input
First of line of input contains a single number nn (1≤n≤2000001≤n≤200000) — length of the sequence which Petya received for his birthday.
Second line of the input contains bracket sequence of length nn, containing symbols "(" and ")".
Output
Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".
Examples
input
Copy
2 )(output
Copy
Yesinput
Copy
3 (()output
Copy
Noinput
Copy
2 ()output
Copy
Yesinput
Copy
10 )))))(((((output
Copy
NoNote
In the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.
In the second example, there is no way to move at most one bracket so that the sequence becomes correct.
In the third example, the sequence is already correct and there's no need to move brackets.
题目类型:栈, 括号匹配
解题目标:判断是否有可能在最多只移动一次的情况下使括号全部匹配。
解题思路:1)在奇数个元素的情况下,永远不可能配对成功。
2)将元素依次入栈,同时把‘(’‘)’能匹配的先消了;
3)入栈结束,若栈为空,已经全部匹配了,甚至不用移动
若栈有两个元素,且刚好‘)''('则移动一次,相互交换即可。
其余情况都不能在一次以内,实现预期效果,则,”No“;
AC代码:
#include <bits/stdc++.h>
#include <vector>
#define rep(x, a, b) for(int x=a; x<=b; x++)
#define inf 0x3f3f3f3f
#define pre(x, a, b) for(int x = a; x >= b; x--)
using namespace std;
const int N= 2e5+10;
int main()
{
int n ;
string s;
scanf("%d", &n);
cin>>s;
if(n%2 == 1)
{
cout<<"No"<<endl;
return 0;
}
else
{
stack<char> st;
rep(i, 0, n-1)
{
if(!st.empty())
{
char temp = st.top();
st.pop();
if(s[i] == ')' && temp == '(') continue;
else st.push(temp);
}
st.push(s[i]);
}
if(st.empty())
{
cout<<"Yes"<<endl;
return 0;
}
else if(st.size() >= 2)
{
char t1 = st.top(); st.pop();
char t2 = st.top(); st.pop();
if(st.size() == 0 && t1 == '(' && t2 ==')' )
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
else
cout<<"No"<<endl;
}
return 0;
}