๋ฌธ์
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 |