C. Bad Sequence
Problem Description:
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 s is called correct if:
- s is empty;
- s is equal to "(t)", where t is correct bracket sequence;
- s is equal to t1t2, i.e. concatenation of t1 and t2, where t1 and t2 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 n (1≤n≤200000) — length of the sequence which Petya received for his birthday.
Second line of the input contains bracket sequence of length n, containing symbols "(" and ")".
Output
Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".
Input1
2 )(
Output1
Yes
Input2
3 (()
Output2
No
Input3
2 ()
Output3
Yes
题意:给出字符串长度,和一段只含左右括号的字符,并定义该字符序列是好的条件为括号匹配或者只通过移一个括号,能使其完全匹配,如果满足上述条件,则输出Yes,否则输出No。
思路:用栈模拟括号匹配.最后判断栈中元素是否只有 ) ( 这 两种括号即可.
AC代码:
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; string str;cin>>str; stack<char> s; if(n%2){ printf("No");return 0; } for(int i=0;i<n;i++){ if(s.empty()){ s.push(str[i]); }else{ if(str[i]==')'){ char temp=s.top(); if(temp=='('){ s.pop(); }else{ s.push(str[i]); } }else{ s.push(str[i]); } } } if(s.empty()){ printf("Yes ");return 0; }else{ if(s.size()!=2){ printf("No");return 0; }else{ char t1=s.top();s.pop(); char t2=s.top();s.pop(); if(t1=='('&&t2==')'){ printf("Yes "); }else{ printf("No "); } } } return 0; }