Rikka with Parenthesis II
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5831
Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them: Correct parentheses sequences can be defined recursively as follows: 1.The empty string "" is a correct sequence. 2.If "X" and "Y" are correct sequences, then "XY" (the concatenation of X and Y) is a correct sequence. 3.If "X" is a correct sequence, then "(X)" is a correct sequence. Each correct parentheses sequence can be derived using the above rules. Examples of correct parentheses sequences include "", "()", "()()()", "(()())", and "(((())))". Now Yuta has a parentheses sequence $S$, and he wants Rikka to choose two different position $i,j$ and swap $S_i,S_j$. Rikka likes correct parentheses sequence. So she wants to know if she can change S to a correct parentheses sequence after this operation. It is too difficult for Rikka. Can you help her?Input
The first line contains a number t(1<=t<=1000), the number of the testcases. And there are no more then 10 testcases with n>100 For each testcase, the first line contains an integers n(1<=n<=100000), the length of S. And the second line contains a string of length S which only contains ‘(’ and ‘)’.Output
For each testcase, print "Yes" or "No" in a line.Sample Input
3 4 ())( 4 ()() 6 )))(((Sample Output
Yes Yes NoHint
For the second sample input, Rikka can choose (1,3) or (2,4) to swap. But do nothing is not allowed.Source
2016 Multi-University Training Contest 8##题意: 括号匹配问题:空、XY、(X) 为合法字串. 给出一个字串,是否可以经过且只经过一次交换操作,使得结果串合法. (不能不交换,不能与自己位置交换)
##题解: 考虑交换操作:(必须换且只能换一次). ①. 如果原串本身就合法,长度为2时:"()"->"No", ")("->"Yes". 长度大于2时一定为"Yes", 因为可以直接交换两个相同的括号. ②. 如果原串非法,那么交换时一定交换的不同的符号(否则没用). 那么符合条件的串一定是把一个 '(' -> ')' 且一个 ')' -> '(' . 那么只考虑变换即可.
考虑如何判断一个串是否合法的过程: 依次处理字符,若是'('则入栈,若是')'则从栈中弹出一个'('. 若没有'('则不合法. 那么此题就是上述过程的变种,在处理过程中允许两次变换. 由于'('->')'的时机不方便考虑, 这里就只考虑')'->'('. ①. 如果当前是'(',直接入栈. ②. 如果当前是')',如果栈非空,则弹出一个'('; 如果栈空就把当前的')'变成'('入栈. (标记最多只能变化一次).
用flag标记是否有将')'变为'('的操作. 结果栈要么为空,要么全是'('. 1. 如果整个字串没有被处理完,那么肯定是"No". 2. 如果flag=0, 那么要求没有'('剩下. 3. 如果flag=1, 那么结果栈中的'('只能是两个. "((" -> "()".
官方题解: 最优情况下一定交换第一个右括号和最后一个左括号,交换后判断一下即可。 时间复杂度 O(n).
##代码: ``` cpp #include