31. 栈的压入、弹出序列(validateStackSequences)

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();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44294385/article/details/112399009