
내가 작성한 코드
import java.util.*;
class Solution {
public int solution(int[] ingredient) {
Stack<Integer> stack = new Stack<>(); // 햄버거 재료 담을 스택
int answer = 0;
for (int i = 0; i < ingredient.length; i++) {
stack.push(ingredient[i]);
// 스택의 크기가 4 이상일 때만 확인
if (stack.size() >= 4) {
// 스택의 마지막 4개 요소가 1, 2, 3, 1 순서인지 확인
int bread1 = stack.get(stack.size() - 4);
int vegetable = stack.get(stack.size() - 3);
int meat = stack.get(stack.size() - 2);
int bread2 = stack.get(stack.size() - 1);
if (bread1 == 1 && vegetable == 2 && meat == 3 && bread2 == 1) {
stack.pop();
stack.pop();
stack.pop();
stack.pop();
answer++;
}
}
}
return answer;
}
}
다른 사람의 코드
class Solution {
public int solution(int[] ingredient) {
int answer = 0;
for (int i = 0; i < ingredient.length - 3; i++) {
if (ingredient[i] == 0)
continue;
// 패턴 발견시 뒤쪽 값을 앞으로 당기고, 앞쪽 4개는 0으로 채움
if (ingredient[i] == 1 && ingredient[i + 1] == 2 && ingredient[i + 2] == 3 && ingredient[i + 3] == 1) {
for (int j = i + 3; j > 0; j--) {
ingredient[j] = (j > 3) ? ingredient[j - 4] : 0;
}
answer++;
}
}
return answer;
}
}
Share article