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.
오늘 문제는 나름 간단했다. 주어진 두 리스트에 대해서 push/pop을 수행했을 때 가능여부만 판단하면 된다.
정답률도 80%로 상당히 높은 편이었다.
무한루프에 걸려버렸다..
myqueue
에 원소가 하나라도 있으면 if
문으로 들어가서 i++
이 안되니까.
class Solution:
def validateStackSequences(self, pushed, popped) -> bool:
myqueue = []
N = len(pushed)
i,j = 0, 0
while i< N:
target = popped[j]
if len(myqueue) >0:
if myqueue[-1] == target:
myqueue.pop(-1)
j +=1
else:
myqueue.append(pushed[i])
i +=1
while j>0:
if len(myqueue) ==0:
return True
target = popped[j]
if myqueue[-1] == target:
myqueue.pop(-1)
j +=1
return False
while
조건문을 잘 맞춰놔도 그 조건에 도달하지 못한다면 의미가 없다.
모든 경우에 대해 i
변수가 N
에 도달할 수 없다면 무한루프에 걸리니까 주의하자.
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
myqueue = []
N = len(pushed)
i,j = 0, 0
while i< N:
if len(myqueue)==0:
myqueue.append(pushed[i])
i +=1
else:
if myqueue[-1] == popped[j]:
myqueue.pop(-1)
j +=1
else:
myqueue.append(pushed[i])
i +=1
while j < N:
if myqueue[-1] == popped[j]:
myqueue.pop(-1)
j +=1
else:
return False
return True