辅助栈
使用一个辅助栈,根据弹出序列的元素,将压栈序列元素压入栈中,比如弹出序列第一个元素是4这时栈为空,则将压栈序列中的[1,2,3,4]压入辅助栈,这时栈顶元素和弹出序列需要弹出的元素相同,则将栈顶元素弹出。如果弹出序列要弹出的元素在辅助栈中找不到则在压栈序列中的剩余元素中寻找,如果找到则压栈,如果找不到则说明该弹出序列不是压栈序列的弹出序列。最后如果辅助栈为空则说明匹配成功。
class Solution {
private Integer index = -1;//记录pushed
public boolean validateStackSequences(int[] pushed, int[] popped) {
LinkedList<Integer> stack = new LinkedList<>();
for(int i = 0; i < popped.length; i++){
if(stack.isEmpty() || stack.peek() != popped[i]){
index = pushStack(pushed,stack, popped[i]);
if(index == pushed.length) return false;
}
stack.pop();
}
return true;
}
/**
* return 返回下一次需要压栈的数字的指针
*/
private int pushStack(int[] pushed, LinkedList<Integer> stack, int val){
for(int i = index+1; i < pushed.length; i++){
if(pushed[i] != val){
stack.push(pushed[i]);
}else{
stack.push(pushed[i]);
return i;//i < pushed.length
}
}
return pushed.length;//没有找到需要压栈的数字
}
}
代码改进
将上面代码写法进行简化
class Solution {
private Integer index = -1;//记录pushed
public boolean validateStackSequences(int[] pushed, int[] popped) {
LinkedList<Integer> stack = new LinkedList<>();
for(int i = 0; i < popped.length; i++){
while(stack.isEmpty() || stack.peek() != popped[i]){
index++;
if(index == pushed.length) return false;
stack.push(pushed[index]);
}
stack.pop();
}
return true;
}
}