解法:
申请一个额外栈,模拟出栈入栈过程,遍历出栈数组,只有辅助栈栈顶元素等于当前出栈数组值时,才会弹出。
我的代码:
public boolean validateStackSequences(int[] pushed, int[] popped) {
if(pushed==null || popped==null) return false;
if(pushed.length != popped.length) return false;
return process(pushed, popped);
}
public boolean process(int[] pushed, int[] poped){
int index1 =0;
int index2 = 0;
Stack<Integer> stack = new Stack<>();
while(index2 < poped.length && index1 < pushed.length){
if(pushed[index1] != poped[index2]){
stack.add(pushed[index1]);
index1 ++;
}
else if(pushed[index1] == poped[index2]){
index2++;
index1 ++;
while(!stack.isEmpty() &&stack.peek() == poped[index2]){
index2++;
stack.pop();
}
}
}
return stack.isEmpty();
}