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

Donghee Lee·2022년 11월 8일
0

Algorithm

목록 보기
17/17
post-thumbnail

문제 링크

햄버거 만들기

문제 요약

햄버거 쌍 만들기..
1,2,3,1이 순서대로 만족하면 햄버거 1개가 만들어진 것으로 간주

요구사항

주어진 Int Array로 만들 수 있는 햄버거 개수 구하기.

func solution(_ ingredient:[Int]) -> Int {
    var stack: [Int] = []
    var result = 0

    for i in ingredient {
        stack.append(i)

        if stack.count >= 4 { 
            let n = stack.count
            if Array(stack[n-4..<n]) == [1, 2, 3, 1] {
                stack = Array(stack[0..<n-4])
                result += 1
            }
        }
    }

    return result
}

처음에 시간 초과로 멘붕이었지만, 결국 풀었다.
근데 시간을 6000ms~8000ms로 통과해서 뭔가 찝찝했음

문제는 stack = Array(stack[0..<n-4]) 부분인데
만약 2,3으로 시작하던 부분이 앞에 있다면 그 부분은 잘라내도 됨(필요 없음)
왜? 2,3으로 시작하면 햄버거를 맹글 수 없응께...

그래서 앞의 2개만 떼와서 임시 저장(temp)한다음 index로 다음 숫자 가져와서 탐색 시작
중요한 건 temp를 stack에서 따로 떼온 뒤 while문에서 temp에만 계속 append하므로 stack과 1,2,3,1을 만족한 부분을 뗀 temp를 더해서 동기화시켜주는 게 포인트

func solution(_ ingredient:[Int]) -> Int {
    var stack: [Int] = [Int]()
    var temp: [Int] = [Int]()
    var result: Int = 0
    let list: [Int] = [1,2,3,1]
    var index: Int = 0
    
    while index != ingredient.count {
        stack.append(ingredient[index])
        index += 1
        if stack.count < 4 { continue }
        if Array(stack[stack.count-4..<stack.count]) == list {
            stack.removeLast(4)
            if stack.count < 3 {
                temp = Array(stack[0..<stack.count])
                stack.removeAll()
            } else {
                temp = Array(stack[stack.count-2..<stack.count])
                stack.removeLast(2)
            }
            result += 1
            while !temp.isEmpty {
                if index == ingredient.count {
                    break
                }
                temp.append(ingredient[index])
                if temp.count > 3 {
                    if Array(temp[temp.count-4..<temp.count]) == list {
                        result += 1
                        index += 1
                        temp.removeLast(4) //햄버거 된 부분만 없애주고
                        stack += temp //그동안 temp에 축적된 부분을 stack에 더하기
                        break
                    }
                }
                index += 1 //여기서 temp에 축적됨
            }
        }
    }
    return result
}

완료된 효율성과 시간
이게 Level1이라니...😢

profile
Better than Yesterday

0개의 댓글