棧的彈出序列問題

給定棧的壓入序列判斷棧的彈出序列是否合法

在這裏插入圖片描述
附上動圖,一看就會
在這裏插入圖片描述
代碼在此:

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack =new Stack<>();
        int i =0;
        for(int num:pushed){
            stack.push(num);
            while(!stack.isEmpty() && stack.peek()==popped[i]){
                stack.pop();
                i++;
            }

        }
        return stack.isEmpty();
    }
}

今日纔來打卡!
五一放假玩耍了4天!!!
釘釘網課時代假中假餘額不足!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章