// 自己代码略繁琐
class Solution {
public boolean validateBookSequences(int[] putIn, int[] takeOut) {
if (putIn.length == 0) {
return true;
}
Stack<Integer> stack = new Stack<>();
for (int i = 0, j = 0; i < putIn.length && j < takeOut.length; ++i) {
stack.push(putIn[i]);
while (!stack.isEmpty() && stack.peek() == takeOut[j]) {
stack.pop();
++j;
}
}
return stack.isEmpty();
}
}
// 参考答案简练!
class Solution {
public boolean validateBookSequences(int[] putIn, int[] takeOut) {
Stack<Integer> stack = new Stack<>();
int j = 0;
for (int num : putIn) {
stack.push(num);
while (!stack.isEmpty() && stack.peek() == takeOut[j]) {
stack.pop();
++j;
}
}
return stack.isEmpty();
}
}
// 自己答案太繁琐!!!
class Solution {
public boolean validateBookSequences(int[] putIn, int[] takeOut) {
if (putIn.length == 0) {
return true;
}
Stack<Integer> stack = new Stack<>();
int i = 0, j = 0;
while (j < takeOut.length) {
if (stack.isEmpty() && i < putIn.length) {
stack.push(putIn[i++]);
} else if (!stack.isEmpty()
&& i < putIn.length
&& stack.peek() != takeOut[j]) {
stack.push(putIn[i++]);
} else if (!stack.isEmpty() && stack.peek() == takeOut[j]) {
stack.pop();
++j;
} else if (i >= putIn.length) {
break;
}
}
return stack.isEmpty();
}
}
##Solution1:
要理解并背诵此题!
参考网址:
https://www.cnblogs.com/AndyJee/p/4651281.html
https://www.nowcoder.com/profile/8709341/codeBookDetail?submissionId=17099336
思路:
1.建立一个辅助栈;
2.将第一个序列的数字压入辅助栈;
3.如果第二个序列的下一个弹出数字刚好是栈顶数字,则直接弹出,第二个序列弹出当前数字,辅助栈也弹出该数字;
4.否则,就把第一个序列中尚未入栈的数字压入辅助栈,直到把第二个序列中下一个需要弹出的数字压入栈顶为止。
5.如果第一个序列的所有数字都已经入栈了,第二个序列中仍然有数字未被弹出,即辅助栈未被清空。则return false。
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
if(pushV.size() == 0) return false;
vector<int> stack;
for(int i = 0,j = 0 ;i < pushV.size();){
stack.push_back(pushV[i++]);
while(j < popV.size() && stack.back() == popV[j]){
stack.pop_back();
j++;
}
}
return stack.empty();
}
};
##Solution2:
20180901重做
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
if (pushV.size() == 0) return false;
stack<int> push_stack;
for (int i = 0,j = 0 ;i < pushV.size();) {
push_stack.push(pushV[i++]);
while (j < popV.size() && push_stack.top() == popV[j]) {
push_stack.pop();
j++;
}
}
return push_stack.empty();
}
};