본문 바로가기
Dev/Algorithm

[프로그래머스] 햄버거 만들기 - Java

by VIPeveloper 2024. 5. 24.
반응형

문제

https://school.programmers.co.kr/learn/courses/30/lessons/133502

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

생각

// 1. StringBuilder 에 저장
// 2. length 가 4 이상이면 한번 체크 해서 substring 하기

코드

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(new int[] {2, 1, 1, 2, 3, 1, 2, 3, 1})); // 2
        System.out.println(solution(new int[] {1, 3, 2, 1, 2, 1, 3, 1, 2})); // 2
    }
    public static int solution(int[] ingredient) {
        int answer = 0;
        // 1. StringBuilder 에 저장
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < ingredient.length; i++) {
            str.append(ingredient[i]);
            // 2. length 가 4 이상이면 한번 체크 해서 substring 하기
            if(str.length()>=4){
                String test = str.substring(str.length()-4);
                if ("1231".equals(test)) {
                    str.delete(str.length()-4,str.length());
                    answer++;
                }
            }
        }
        return answer;
    }
}

다른 사람 풀이

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(new int[] {2, 1, 1, 2, 3, 1, 2, 3, 1})); // 2
        System.out.println(solution(new int[] {1, 3, 2, 1, 2, 1, 3, 1, 2})); // 2
    }
    public static int solution(int[] ingredient) {
        int[] stack = new int[ingredient.length];
        int sp = 0;
        int answer = 0;
        for (int i : ingredient) {
            stack[sp++] = i;
            if (sp >= 4 && stack[sp - 1] == 1
                    && stack[sp - 2] == 3
                    && stack[sp - 3] == 2
                    && stack[sp - 4] == 1) {
                sp -= 4;
                answer++;
            }
        }
        return answer;
    }
}
반응형