Sangmun

Leet code Validate Stack Sequences 본문

알고리즘/리트코드

Leet code Validate Stack Sequences

상상2 2023. 4. 13. 20:00

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

 

Validate Stack Sequences - LeetCode

Can you solve this real interview question? Validate Stack Sequences - Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack

leetcode.com

 

class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:

        # pop을 이용하기 위해 역으로 정렬
        popped = popped[::-1]
        pushed_bucket = []

        # pushed에서 하나씩 iter하면서 popped와 일치하는것이 있는지 확인
        for pushed_number in pushed:

            # popped에 일치하는 것이 있다면 로직 진입
            if pushed_number == popped[-1]:
                
                pushed_bucket.append(pushed_number)
                now = pushed_number

                # 이전에 삽입한 원소들도 일치하는것이 있는지 확인하면서
                # 일치한다면 제거
                while True:
                    if now == popped[-1]:
                        pushed_bucket.pop()
                        popped.pop()
                        
                        if len(pushed_bucket):
                            now = pushed_bucket[-1]
                        else:
                            break
                    else:
                        break
            
            # popped[-1]과 일치하지 않는다면 일단 삽입
            else:
                pushed_bucket.append(pushed_number)

        # 아직 남아있는게 있다면 False
        if popped:
            return False
        else:
            return True

'알고리즘 > 리트코드' 카테고리의 다른 글

459. Repeated Substring Pattern  (0) 2023.08.12
283. Move Zeroes  (0) 2023.05.04
Palindrome  (0) 2023.04.27
516. Longest Palindromic Subsequence  (0) 2023.04.22
662. Maximum Width of Binary Tree  (0) 2023.04.20
Comments