牛客_剑指offer题集——栈的压入弹出序列(java实现)

题目链接:

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:通过代码试图模拟出相应的出栈序列,若失败,则返回false,否则true

实现代码:

package niuke;

import java.util.Stack;

public class 栈的压入弹出序列 {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer> stack = new Stack<>();
        int i = 0;
        int j = 0;
        stack.push(pushA[i++]);
        while(j < popA.length){//模拟出栈
            while(popA[j]!=stack.peek()){
                if(i==pushA.length) return false;
                stack.push(pushA[i++]);
            }
            stack.pop();
            ++j;
        }
        return true;
    }
}

代码已经ac

希望对大家有所帮助

以上

猜你喜欢

转载自www.cnblogs.com/lavender-pansy/p/12441225.html
今日推荐