剑指 Offer 31. 栈的压入、弹出序列
题目:
思路:
看了剑指的思路做的,虽然代码不一样,但是代码都显得乱。简单说下思路:
思路一:
1.按照push的顺序往stack中push,知道poped[0]
2.然后进行stack.pop,如果poped[0++]和stack.peek() 不相等了。那么在pushed里接着找peek,没找到就退出,找到就向1一样,继续往stack中放置
3.注意:思路就是这个思路,自己写的时候一直没有对pushed的位置进行判断导致一直提交报错,睡了一觉,多加了一个参数,if校验也变少了,直接过了
(语言行描述确实有点乱,show code or picture)
思路二:
其实上面的思路容易理解,但是代码的实现还是较为复杂,没有什么章法。if退出条件也试了多次,翻了翻其他人的题解,还是这种思路只不过简化了下——按照push的顺序,每次放完后,判断是否和pushed相等,相等就一直pop。当push放完后,直接判断是否pop完成即可。
题解:
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int popedInt = 0;
for (int i = 0; i < pushed.length; i++) {
stack.push(pushed[i]);
// 每次push后就进行判断是否要pop
while (!stack.isEmpty() && stack.peek() == popped[popedInt]) {
stack.pop();
popedInt++;
}
}
// 直接返回结果
return popedInt == popped.length;
}
}
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
// 空,或者一个为空的判断
if (pushed.length == 0 && popped.length == 0) {
return true;
}
if (pushed.length == 0 || popped.length == 0) {
return false;
}
// 下次pushed开始的地方
int temp = -1;
// pushed的计数,到头了并且stack还没pop完就退出
int pushInt = 0;
Stack<Integer> stack = new Stack<>();
// poped的技术
int count = 0;
while (true) {
for (int i = temp+1; i < pushed.length; i++) {
stack.push(pushed[i]);
pushInt = i;
if (pushed[i] == popped[count]) {
temp = i;
break;
}
}
while ( !stack.isEmpty() && stack.peek() == popped[count]) {
stack.pop();
count++;
}
// pop数组验证完了,就退出
if (count > popped.length - 1 && stack.isEmpty()) {
return true;
}
// 引入一个pushed数组的计数,如果用完了,但是stack还没pop完就退出
if (pushInt >= pushed.length - 1) {
if (stack.isEmpty()) {
return true;
}
return false;
}
}
}
}