-
[프로그래머스, Lv1] 햄버거알고리즘 문제/Java 2024. 8. 19. 23:26
코딩테스트 연습 - 햄버거 만들기 | 프로그래머스 스쿨 (programmers.co.kr)
문제설명
햄버거 가게에서 일을 하는 상수는 햄버거를 포장하는 일을 합니다. 함께 일을 하는 다른 직원들이 햄버거에 들어갈 재료를 조리해 주면 조리된 순서대로 상수의 앞에 아래서부터 위로 쌓이게 되고, 상수는 순서에 맞게 쌓여서 완성된 햄버거를 따로 옮겨 포장을 하게 됩니다. 상수가 일하는 가게는 정해진 순서(아래서부터, 빵 – 야채 – 고기 - 빵)로 쌓인 햄버거만 포장을 합니다. 상수는 손이 굉장히 빠르기 때문에 상수가 포장하는 동안 속 재료가 추가적으로 들어오는 일은 없으며, 재료의 높이는 무시하여 재료가 높이 쌓여서 일이 힘들어지는 경우는 없습니다.
예를 들어, 상수의 앞에 쌓이는 재료의 순서가 [야채, 빵, 빵, 야채, 고기, 빵, 야채, 고기, 빵]일 때, 상수는 여섯 번째 재료가 쌓였을 때, 세 번째 재료부터 여섯 번째 재료를 이용하여 햄버거를 포장하고, 아홉 번째 재료가 쌓였을 때, 두 번째 재료와 일곱 번째 재료부터 아홉 번째 재료를 이용하여 햄버거를 포장합니다. 즉, 2개의 햄버거를 포장하게 됩니다.
상수에게 전해지는 재료의 정보를 나타내는 정수 배열 ingredient가 주어졌을 때, 상수가 포장하는 햄버거의 개수를 return 하도록 solution 함수를 완성하시오.
제한사항
- 1 ≤ ingredient의 길이 ≤ 1,000,000
- ingredient의 원소는 1, 2, 3 중 하나의 값이며, 순서대로 빵, 야채, 고기를 의미합니다.
접근 방법
우선 나는 해당 문제를 처음 접했을 때에는 Stack이 제일 먼저 떠올랐다.
재료를 추가했을 때, 햄버거가 완성 된다면 뒤에서부터 4개를 제거해야하기 때문이다.
하지만, 재료가 추가 될 때마다 뒤에서 4개를 꺼낸 후, 햄버거인지 확인하고 다시 넣는 과정이
비효율적이라는 생각이 들어 문자열로 하면 어떨까 ? 하는 생각이 들었다.
재료가 들어 올 때마다 StringBuilder.append메서를 통해 재료를 문자열 뒤에 연결해주고,
마지막 4문자의 SubString한 결과값이 "1231"인 경우, 해당 내용을 삭제하고 answer + 1 하는 방식으로 구현했다.
최종 코드
더보기class Solution { public int solution(int[] ingredient) { int answer = 0; StringBuilder patty = new StringBuilder(); for(int n : ingredient) { patty.append(String.valueOf(n)); if (patty.length() >= 4 && patty.substring(patty.length() - 4).equals("1231")) { ++answer; patty.delete(patty.length() - 4, patty.length()); } } return answer; } }
후기
코드의 부피와 시간 복잡도는 확 줄였지만,
마지막 문자열이 "1231"인지 확인하는 과정에서 SubString함수를 통해 String객체를 계속 생성한다는
문제가 존재했다.
해당 과정을 차라리 charAt과 같은 메서드를 통해
맨 뒤 4개의 문자를 확인하여 Check하는 것은 어땟을까 하는 아쉬움이 남았다.
'알고리즘 문제 > Java' 카테고리의 다른 글
[프로그래머스, Lv1] 개인정보 수집 유효기간 (0) 2024.08.21 [프로그래머스, Lv1] 바탕화면 정리 (0) 2024.08.20 [프로그래머스, Lv1] 문자열 자르기 (0) 2024.08.13 [프로그래머스, Lv1] 체육복 (0) 2024.08.12 [프로그래머스, Lv1] 로또의 최고 순위와 최저 순위 (0) 2024.08.06