31. 栈的压入、弹出序列(validateStackSequences)
1. python
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack,i =[],0
for num in pushed:
stack.append(num)
while stack and stack[-1]==popped[i]:
stack.pop()
i+=1
return not stack
2. Java
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<Integer>();
int i =0;
for(int num:pushed){
stack.push(num);
while(!stack.isEmpty() && stack.peek()==popped[i]){
stack.pop();
i++;
}
}
return stack.isEmpty();
}
}