Validate Stack Sequences

Sett·2021년 8월 15일
0

문제

https://leetcode.com/problems/validate-stack-sequences/

문제 접근

  1. pushed를 뽑다가 poped의 첫번째 숫자하고 pushed의 방금 뽑은 숫자하고 같아야만 뽑을 수 있나..? 어쨌든 앞에서 부터 뽑아서 Queue를 적용하는 건 맞는데, 구체적인 이해가 안됐음.
  2. pushed 뽑은걸 어디다 저장해놓고 저장해놓은 마지막 숫자가 poped의 첫번째 숫자와 동일하면 poped을 하기로 함.
  3. 이런식으로 해서 둘다 비워지면 되는 거 아닌가..?

소스 코드

    func validateStackSequences(_ pushed: [Int], _ popped: [Int]) -> Bool {
        var result: [Int] = []
        var mypoped = popped
        for item in pushed {
            result.append(item)
            
            while !result.isEmpty && result.last == mypoped.first {
                result.removeLast()
                mypoped.removeFirst()
            }
        }
        return result.count == 0 ? true : false
    }
profile
안녕하세요

0개의 댓글

관련 채용 정보