프로그래머스 - 햄버거 만들기 ( Stack )

youngkyu MIn·2023년 12월 25일

문제링크 - 프로그래머스 - 햄버거 만들기

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public int solution(int[] ingredient) {
        int count = 0;
        List<Integer> list = new ArrayList<>();

        for (int i : ingredient) {
            list.add(i);

            if (list.size() >= 4) {
                int size = list.size();
                if (list.get(size - 4) == 1 && list.get(size - 3) == 2 &&
                    list.get(size - 2) == 3 && list.get(size - 1) == 1) {
                    count++;
           
                    for (int i = 0; i < 4; i++) {
                        list.remove(list.size() - 1);
                    }
                }
            }
        }

        return count;
    }
}

일단 리스트로 풀었다.

if (list.get(size - 4) == 1 && list.get(size - 3) == 2 &&
                    list.get(size - 2) == 3 && list.get(size - 1) == 1) {

순서대로 리스트에 추가하면서 리스트의 끝-4 부터해서 빵 고기 야채 빵 순서 다시말해 1 , 2, 3, 1 순서인지 검사하고 순서가 맞으면 포장하는 방식으로 코드가 돌아간다.

후입선출(LIFO) 이 꼭 필요한 문제조건은 아니지만 예전에 알아봤던 Stack 클래스로 풀어봐도 재밌을 것 같아서 한번 해봤다.

import java.util.Stack;

public class Solution {
    public int solution(int[] ingredient) {
        int count = 0; 
        Stack<Integer> stack = new Stack<>();

        for (int i : ingredient) {
            stack.push(i);

            if (stack.size() >= 4) {
                if (stack.get(stack.size() - 4) == 1 && stack.get(stack.size() - 3) == 2 &&
                    stack.get(stack.size() - 2) == 3 && stack.get(stack.size() - 1) == 1) {                  
                    count++;
                    stack.pop(); 
                    stack.pop(); 
                    stack.pop(); 
                    stack.pop();
                }
            }
        }

        return count; 
    }
 }

List 로 푼 로직이랑 다를게 없다. 다만 stack.pop() 이 네번 이루어지고 stack 은 후입선출의 규칙이 있기 때문에 햄버거의 포장 순서는 빵-야채-고기-빵 이겠지만 pop 되는 순서는 빵-고기-야채-빵 으로 거꾸로가 될 것이다. 후입선출의 문제조건이 있다면 활용하기 좋을 것 같다.


예전에 알아봤지만 기억이 잘 안나니까 뤼와인드 한번 하고 넘어가자


Stack 은 Vector 클래스를 상속 받으며 java.util 패키지에 속한다.

주요메서드

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        // 요소 삽입
        stack.push(1);
        stack.push(2);
        stack.push(3);

        // 최상단 요소 확인
        System.out.println("Top element: " + stack.peek()); // 출력: 3

        // 요소 제거
        while (!stack.empty()) {
            System.out.println(stack.pop());
        }

        // 스택이 비어있는지 확인
        System.out.println("Is stack empty? " + stack.empty()); // 출력: true
    }
}
profile
한 줄 소개

0개의 댓글