1218. [S/W 문제해결 기본] 4일차 - 괄호 짝짓기
4종류의 괄호문자들로 이루어진 문자열이 주어진다. 이때 괄호들의 짝이 모두 맞는지 판별하라.
stack 자료구조를 활용한다.
주어진 문자열의 각 문자의 방향에 따라 분기한다.
< { [ (
) 일 때 :push()
> } ] )
) 일 때 :peek()
확인 // top에 있는 문자가 무엇인지pop()
!return false
! 모든 문자를 확인 후, stack이 비었는지 확인한다!
비어있지 않으면 false
!! - 짝이 맞지 않는 것
import java.util.Scanner;
import java.util.Stack;
import java.io.FileInputStream;
class Solution
{
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int T = 10;
for(int test_case = 1; test_case <= T; test_case++)
{
int size = sc.nextInt();
String input = sc.next();
System.out.printf("#%d %d\n", test_case, check(input, size)?1:0);
}
}
public static boolean check(String input, int size) {
Stack<Character> stack = new Stack<>();
for (int i=0; i<size; i++) {
if (isOpen(input.charAt(i))) {
stack.push(input.charAt(i));
} else {
if (isClose(input.charAt(i), stack.peek())) stack.pop();
else return false;
}
}
if (stack.empty()) return true;
return false;
}
public static boolean isOpen(char input) {
if (input == '{' || input == '[' || input == '(' || input == '<') return true;
else return false;
}
public static boolean isClose(char input, char top) {
if (input == '}' && top == '{') return true;
else if (input == ']' && top == '[') return true;
else if (input == ')' && top == '(') return true;
else if (input == '>' && top == '<') return true;
else return false;
}
}
정규식을 쓰지 않았기 때문에 조건을 확인하는 부분이 하드코딩이었다. 너무 구구절절이라 가독성이 떨어지기 때문에 boolean type의 isOpen()
, isClose()
함수로 빼줬다.