LeetCode 946: Validate Stack Sequences

이원희·2021년 3월 3일
0

📝 PS

목록 보기
60/65
post-thumbnail

문제 풀이

Array지만 stack처럼 취급할 stack 변수를 선언했다.
pushed를 돌면서 stack에 더해주었다.
pop해야 하는 수와 현재 stack의 가장 마지막이 같다면 pop할 수 있다.

func validateStackSequences(_ pushed: [Int], _ popped: [Int]) -> Bool {
    var stack: [Int] = [], index = 0
    for push in pushed {
        stack.append(push)
        while index < popped.count && popped[index] == stack.last {
            stack.popLast()
            index += 1
        }
    }
    return stack.isEmpty
}

LeetCode

0개의 댓글