
문자열이 주어질 때 괄호
()와[]가 올바르게 짝지어져 있는지 판별하는 문제.
.만 입력되면 종료. 올바르면yes, 아니면no출력.
. 이면 종료(, [ 는 스택에 push), ] 가 나오면 스택에서 pop → 짝이 맞는지 확인, 스택이 비어있거나 짝이 안 맞으면 falsetrue(, ) / [, ] 두 쌍을 동시에 처리해야 하므로 pop한 값과 현재 닫는 괄호 비교 필수import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals(".")) break;
boolean result = check(line);
System.out.println(result ? "yes" : "no");
}
scanner.close();
}
public static boolean check(String line) {
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '(' || c == '[') stack.push(c == '(' ? (int) '(' : (int) '[');
if (c == ')' || c == ']') {
if (stack.isEmpty()) return false;
int top = stack.pop();
if (c == ')' && top != '(') return false;
if (c == ']' && top != '[') return false;
}
}
return stack.isEmpty();
}
}
abcd( 같이 push만 되는 경우, false로 판단하지 않을 수 있어서 stack.isEmpty()로 체크를 해줘야 한다.check() 함수 안에서 줄마다 스택이 초기화되게 만들어야 한다.