括号匹配的检验
标准输入输出
题目描述:
采用栈实现,练习进栈入栈函数的编写.
输入:
输入的第一行包含一个数,n
n表示要用例的个数
接下来是n行由括号构成的字符串,包含‘(’、‘)’、‘[’、‘]’。
输出:
对每一测试用例,用一行输出结果,如果匹配,输出“YES”,否则输出“NO”
输入样例:
2
[([][]())]
)[]()
输出样例:
YES
NO
参考:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0) {
String str = sc.next();
Stack<Character> st = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
char top = (char) -1;
if (!st.isEmpty()) {
top = st.peek();
}
if ((top == '[' && ch == ']') || (top == '(' && ch == ')')) {
st.pop();
} else {
st.push(ch);
}
}
if (st.isEmpty()) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}