题解 | #栈的压入、弹出序列#

栈的压入、弹出序列

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

import java.util.*;


public class Solution {

    public boolean IsPopOrder (int[] pushV, int[] popV) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        if (pushV.length != popV.length) {
            return false;
        }
        int push = 0;
        for (int i = 0; i < popV.length; i++) {
            if (stack.size() == 0) {
                stack.push(pushV[push++]);
            }
            if (stack.peek() == popV[i]) {
                stack.pop();
            }else {
                while (stack.peek() != popV[i]) {
                    if (push == pushV.length) {
                        return false;
                    }
                    stack.push(pushV[push++]);
                }
                stack.pop();
            }
        }
        
        return true;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务