import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
for(int i=0; i<t; i++){
String ps = br.readLine();
if(ps.startsWith(")") || ps.endsWith("(")) sb.append("NO\n");
else {
char[] bits = ps.toCharArray();
Stack<Character> stack = new Stack<>();
for(char c : bits){
if(c == '(') stack.push('(');
else if(c == ')' && stack.isEmpty()) {
stack.push(')');
break;
} else stack.pop();
}
if(stack.size() != 0) sb.append("NO\n");
else sb.append("YES\n");
}
}
System.out.println(sb);
br.close();
}
}
스택을 이용한 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
for(int i=0; i<t; i++){
String ps = br.readLine();
if(ps.startsWith(")") || ps.endsWith("(")) sb.append("NO\n");
else {
char[] bits = ps.toCharArray();
int a = 0;
boolean flag = true;
for(char c : bits){
if(c == '(') a++;
else a--;
if(a < 0) flag = false;
}
if(a == 0 && flag) sb.append("YES\n");
else sb.append("NO\n");
}
}
System.out.println(sb);
br.close();
}
}
'Coding Test > 백준' 카테고리의 다른 글
[백준/자바] 2164 - 카드2 (0) | 2023.05.12 |
---|---|
[백준/자바] 2566 - 최댓값 (0) | 2023.05.11 |
[백준/자바] 2738 - 행렬 덧셈 (0) | 2023.05.11 |
[백준/자바] 1157 - 단어 공부 (0) | 2023.05.11 |
[백준/자바] 2444 - 별 찍기 - 7 (0) | 2023.05.11 |