import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt(); sc.nextLine();
for(int i=0; i<testcase; i++) {
Stack <String> stack = new Stack<>();
String str = sc.nextLine();
for(int j=0; j<str.length(); j++) {
String first = str.substring(j, j+1);
if(first.equals("(")) {
stack.push(first);
}
else {
if(stack.isEmpty()) {
System.out.println("NO");
break;
}
else {
stack.pop();
}
}
if(j == str.length()-1) {
if(stack.isEmpty()) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
}
}
}
기본적으로 스택으로 구성을 했다. (큐로해도 상관은 없을 것 같다.)
그리고 "(" 가 들어왔을 땐, 그냥 스택에 쌓고
")" 가 들어 왔을땐, 스택이 비어있다면 바로 NO 출력, 스택에 값이 있다면, 값을 빼준다.
그리고 최종적으로 스택이 비어있다면 YES 아니면 NO 를 출력해준다.
'Algorithm > 문자열' 카테고리의 다른 글
Programmers 신규 결과 받기 (0) | 2022.01.17 |
---|---|
Programmers 신규 아이디 추천 (0) | 2022.01.16 |
Programmers 신고 결과 받기 (0) | 2022.01.16 |