剑指31:栈的压入、弹出序列

传送门

nowcoder
leetcode

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。

C++ 代码 - nowcoder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
使用一个栈
*/
class Solution {
public:
bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {
if (pushV.empty() || popV.empty() || pushV.size() != popV.size()) return false;

stack<int> stk;
int length = pushV.size(), popIndex = 0;
for (int i = 0; i < length; i ++) {
stk.push(pushV[i]);
while (popIndex < length && !stk.empty() && stk.top() == popV[popIndex]) {
cout << stk.top() << endl;
stk.pop();
popIndex ++;
}
}

return stk.empty();
}
};

C++ 代码 - leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool validateBookSequences(vector<int>& putIn, vector<int>& takeOut) {
if (putIn.empty() && takeOut.empty()) return true;
if (putIn.empty() || takeOut.empty() || putIn.size() != takeOut.size()) return false;

stack<int> stk;
int length = putIn.size(), popIndex = 0;
for (int i = 0; i < length; i ++) {
stk.push(putIn[i]);
while (popIndex < length && !stk.empty() && stk.top() == takeOut[popIndex]) {
stk.pop();
popIndex ++;
}
}

return stk.empty();
}
};

剑指31:栈的压入、弹出序列
https://lcf163.github.io/2021/01/30/剑指31:栈的压入、弹出序列/
作者
乘风的小站
发布于
2021年1月30日
许可协议