題目
Description
現在,有一行括号序列,請你檢查這行括号是否配對。
Input
第一行輸入一個數N<=1000)後面是N行由組成的括号序列~
Output
每組輸入資料的輸出占一行,如果該字元串中所含的括号是配對的,則輸出Yes,如果不配對則輸出No
Sample Input
3
[(])
(])
([])
Sample Output
No
No
Yes
代碼塊
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner cn = new Scanner(System.in);
int t = cn.nextInt();
Stack<Character> sta = null;
while (t-- > ) {
String str = cn.next();
if (str.length() % == )
System.out.println("No");
else {
sta = new Stack<Character>();
for (int i = ; i < str.length(); i++) {
//是空的就入棧
if (sta.isEmpty())
sta.push(str.charAt(i));
//有比對的就出棧
else if (sta.peek() == '[' && str.charAt(i) == ']'
|| sta.peek() == '(' && str.charAt(i) == ')'
|| sta.peek() == '{' && str.charAt(i) == '}')
sta.pop();
//不比對的也入棧
else
sta.push(str.charAt(i));
}
if (sta.isEmpty())
System.out.println("Yes");
else
System.out.println("No");
}
}
cn.close();
}
}