매일 Algorithm

신재원·2023년 11월 16일
0

Algorithm

목록 보기
237/243

백준 28278번 스택2


import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Stack<Integer> store = new Stack<>();
        StringBuilder output = new StringBuilder();
        int size = in.nextInt();

        for (int i = 0; i < size; i++) {
            int number = in.nextInt();

            // 1. 입력값이 1일 경우
            if (number == 1) {
                int input = in.nextInt();
                store.push(input);
            }

            // 2. 입력값이 2일 경우
            if (number == 2) {
                if (!store.isEmpty()) {
                    output.append(store.pop()).append("\n");
                } else {
                    output.append("-1\n");
                }
            }

            // 3. 입력값이 3일 경우
            if (number == 3) {
                output.append(store.size()).append("\n");
            }

            // 4. 입력값이 4일 경우
            if (number == 4) {
                if (store.isEmpty()) {
                    output.append("1\n");
                } else {
                    output.append("0\n");
                }
            }

            // 5. 입력값이 5일 경우
            if (number == 5) {
                if (!store.isEmpty()) {
                    output.append(store.peek()).append("\n");
                } else {
                    output.append("-1").append("\n");
                }
            }
        }
        System.out.println(output.toString());
    }
}

백준 4949번 (균형잡힌 세상)



import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (true) {
            String words = in.nextLine();

            if (words.equals(".")) break;

            System.out.println(answer(words));
        }
    }

    private static String answer(String words) {
        Stack<Character> store = new Stack<>();

        for (char word : words.toCharArray()) {
            // 1. 여는 괄호 일경우
            if (word == '(' || word == '[') {
                store.push(word);
            }

            // 2. 닫는 괄호 일경우
            else if (word == ')') {
                if (store.isEmpty() || store.peek() != '(') {
                    return "no";
                } else {
                    store.pop();
                }
            } else if (word == ']') {
                if (store.isEmpty() || store.peek() != '[') {
                    return "no";
                } else {
                    store.pop();
                }
            }
        }

        // 3. stack 객체가 비어있다는것은 괄호가 다 짝을 이룬것 or
        // 괄호가 처음부터 없는 문자열
        if (store.isEmpty()) {
            return "yes";
        } else {
            return "no";
        }
    }
}

0개의 댓글