栈的压入、弹出序列
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&&tqId=11174&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目思路:
使用一个栈来进行入栈,然后当栈不为空则开始跟popA数组进行比较,若相等则将该元素弹出栈
最后看栈是否为空,如果为空则证明popA是pushA的出栈数组。
public boolean IsPopOrder(int [] pushA,int [] popA) { if(pushA.length == 0 && popA.length == 0) return true; Stack<Integer> stack = new Stack<>(); int n = pushA.length; for(int pushIndex = 0,popIndex = 0;pushIndex < n; pushIndex++){ stack.push(pushA[pushIndex]); while(popIndex < n && !stack.isEmpty() && stack.peek()==popA[popIndex]){ stack.pop(); popIndex++; } } return stack.isEmpty(); }
剑指offer 文章被收录于专栏
为刷过的每一道题都书写一篇题解,便于重复练习~