๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

[Leetcode] Validate Stack Sequences (#946)

 

 

๋ฌธ์ œ 

 

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, or false otherwise.

 

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

 

 

ํ•ด์„ค ์ฝ”๋“œ 
class Solution(object):
    def validateStackSequences(self, pushed, popped):
        stack = []
        j = 0
        for val in pushed:
            stack.append(val)
            # stack ์— ์›์†Œ๊ฐ€ ์กด์žฌํ•˜๊ณ  stack[-1] ์ด popped[j] ์™€ ๊ฐ™์œผ๋ฉด stack์„ pop ์‹œํ‚ด
            while stack and stack[-1] == popped[j]:
                stack.pop()
                j += 1
        # stack์ด ๋น„๋ฉด false ์ธ๋ฐ ์—ฌ๊ธฐ์„œ๋Š” ๋น„์–ด์•ผ true ์ด๊ธฐ ๋•Œ๋ฌธ์— not์„ ๋ถ™์—ฌ์คŒ
        return not stack
๋ถ„์„ > while ๋ฌธ์„ ์ž‘์„ฑํ•  ๋•Œ๋Š” ํ•ญ์ƒ ์กฐ๊ฑด์„ ๊ผผ๊ผผํžˆ ์ ๋Š” ์—ฐ์Šต์„ ํ•˜์ž. ๊ทธ๋ฆฌ๊ณ  ์ด ๋ฌธ์ œ๋ฅผ ํ†ตํ•ด return not ์ด๋ผ๋Š” ๊ฐœ๋…์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  popped ๋ฐฐ์—ด๋„ ๊ฐ™์ด pop ํ•˜์ง€ ์•Š์•„๋„ j ๋ฅผ ์ฆ๊ฐ€์‹œํ‚ด์œผ๋กœ์จ ๋น„๊ตํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ๋„ ์ƒˆ๋กญ๊ฒŒ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. 

'Algorithm > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode] Group Anagrams  (0) 2022.05.18
[Leetcode] Last Moment Before All Ants Fall Out of a Plank (#1503)  (0) 2022.04.21
[Leetcode] Create Target Array in the Given Order (#1389)  (0) 2022.04.21
[Leetcode] Clumsy Factorial (#1006)  (0) 2022.04.21
[Leetcode] Print Words Vertically (#1324)  (0) 2022.04.20