내 풀이 - Stack 사용 , 백준에서 비슷한 문제를 풀어봄
import java.util.Stack;
class Solution {
final int[] hamberger = {1, 2, 3, 1};
public int solution(int[] ingredient) {
int answer = 0;
Stack<Integer> stack = new Stack<>();
for (int val : ingredient) {
stack.push(val);
if (stack.size() >= 4 && stack.peek() == 1) {
int changeIdx = stack.size() - 4;
boolean makeFlag = true;
for (int tmpIdx = 0; tmpIdx < 4; tmpIdx++) {
if (stack.get(changeIdx + tmpIdx) != hamberger[tmpIdx]) {
makeFlag = false;
break;
}
}
if (makeFlag) {
for (int j = 0; j < 4; j++) {
stack.pop();
}
answer++;
}
}
}
return answer;
}
}
다른 사람 풀이 - 배열 사용 - 속도 매움 빠름
class Solution {
public 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;
}
}