개발자-H 입니다.

BOJ - 균형잡힌 세상 본문

Algorithm/문제 풀이

BOJ - 균형잡힌 세상

개발자-H 2021. 9. 3. 07:08

https://www.acmicpc.net/submit/4949/32913451

 

로그인

 

www.acmicpc.net

 

  • 괄호 문자열을 연습하기 좋은 문제이다.
  • 괄호의 순서는 스텍의 성질을 이용하여 균형잡혀 있는지 알 수 있다.

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;


public class Main {
    public static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        while(true) {
            String line = br.readLine();
            if(line.equals(".")) {
                break;
            }

            checkBalanceLine(line);
        }
    }

    private static void checkBalanceLine(String line) {
        Stack<Character> stack = new Stack<>();

        for(char word : line.toCharArray()) {
            if(word == '(' || word == '[') {
                stack.push(word);
            }

            if(word == ')') {
                if(stack.isEmpty()) {
                    System.out.println("no");
                    return;
                }
                if(stack.peek() != '(') break;
                stack.pop();
            }

            if(word == ']') {
                if(stack.isEmpty()) {
                    System.out.println("no");
                    return;
                }
                if(stack.peek() != '[') break;
                stack.pop();
            }
        }

        if(stack.isEmpty()) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
    }
}

'Algorithm > 문제 풀이' 카테고리의 다른 글

BOJ - 케빈 베이컨의 6단계 법칙  (0) 2021.09.05
BOJ - 2×n 타일링  (0) 2021.09.04
프로그래머스 - 모음 사전(5주차 위클리)  (0) 2021.09.02
BOJ - 경로 찾기  (0) 2021.09.01
BOJ - 듣보잡  (0) 2021.08.31
Comments