

한 쌍의 괄호 기호"( )"의 개수를 구하는 문제이다. 처음엔 '(' 와 ')' 의 개수만 맞으면 된다고 생각하여 open과 close의 개수를 count해 동일한지 비교하는 형태로 진행했지만 VPS는 완성된 괄호형태의 개수를 말하는 것이었다.
단순히 괄호들의 개수를 더하고 빼며 구하긴 힘들다고 생각했다. 하지만 스텍을 사용하면 '(' 가 항상 먼저 와야하는 문제를 해결할 수 있다.
public static boolean isValidParentheses(String input) {
Stack<Character> stack = new Stack<>();
for (char ch : input.toCharArray()) {
if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
}
}
return stack.isEmpty();
}
')' 괄호는 push할 필요 없는가?
')' 를 따로 push할 필요는 없다. 닫는 괄호를 만났을 때 단순히 스텍에서 pop하여 짝을 확인하는 것이 목적이기 때문이다.
그러므로 input 문자열의 각 문자를 순회하며 각 문자를 순서대로 ch 변수에 저장하고, 루프의 각 반복에서 ch 변수를 사용하여 작업을 수행한다.
import java.util.Scanner;
import java.util.Stack;
public class beak_9012 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
sc.nextLine();
for (int i = 0; i < T;i++) {
String input = sc.nextLine();
if (isValidParentheses(input)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
public static boolean isValidParentheses(String input) {
Stack<Character> stack = new Stack<>();
for (char ch : input.toCharArray()) {
if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
}
}
return stack.isEmpty();
}
}