프로그래머스 - 햄버거 만들기
class Solution {
public int solution(int[] ingredient) {
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i : ingredient) {
sb.append(i);
if(sb.length() >= 4) {
int lastIndex = sb.length() - 1;
if(sb.charAt(lastIndex - 3) == '1' && sb.charAt(lastIndex - 2) == '2' && sb.charAt(lastIndex - 3) == '3' && sb.charAt(lastIndex) == '1') {
sb.delete(lastIndex-3, lastIndex + 1);
count++;
}
}
}
return count;
}
}
- 재료를 넣어가면서, 4개 이상이 되면 햄버거 포장할 수 있는지 확인한다.
- 포장할 수 있다면 StringBuilder에서 삭제시킨다.
- 하나씩 집어넣으므로 검사할 때 for문 검사 안해도 됨
- StringBuilder 메서드
- delete(a, M+1) : a~M까지 삭제
- deleteCharAt(a) : a위치 삭제
- insert(2, "llo") : 2번 인덱스에 "llo" 문자열 삽입
- StringBuilder 메서드 출처
- 기존에는 배열 전체를 stream으로 하고 String으로 만들고, 1231 패턴을 subString 했는데 타임아웃이 떴다..
- subString 말고 replace("1231", "")도 해봤는데, replace로 없어져서 땡겨진 문자열이 다시 1231을 만들면 이것 역시도 바꿔버린다.. 너무 열일함..