思路一:建立两个队列,一个栈
遇到一个坑:(int) stack.peek() == (int) queue2.peek(),最开始,我没用int强转,比较的其实是地址值,而不是int值。导致了错误。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
LinkedList<Integer> queue2 = new LinkedList<>();
for (int i : popped) {
queue2.add(i);
}
LinkedList<Integer> queue1 = new LinkedList<>();
for (int i : pushed) {
queue1.add(i);
}
// 建立一个栈
Stack<Integer> stack = new Stack<>();
while (!queue1.isEmpty()) {
stack.push(queue1.pop());
// 栈不为空
while (!stack.isEmpty() && (int) stack.peek() == (int) queue2.peek()) {
stack.pop();
queue2.pop();
}
}
return stack.isEmpty();
}
}
思路二:几乎类似,只不过 不创建队列:
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int j = 0;//需要对比的序号
for(int i = 0; i<pushed.length; i++){
stack.push(pushed[i]);
while(!stack.isEmpty() && j<popped.length && stack.peek() == popped[j]){
stack.pop();
j ++;
}
}
return stack.isEmpty();
}
}