- Stack Push-Pop Sequence
中文English
Given a push sequence and pop sequence of a stack. Decide whether there are legal sequences.
Example
Example 1:
Input: push = [1, 2, 3], pop = [3, 2, 1]
Output: True
Explanation: Push 1, 2, 3 and pop 3, 2, 1.
Example 2:
Input: push = [1, 2, 3], pop = [3, 1, 2]
Output: False
Explanation:
If we want to first pop 3, the 1 and 2 must already in the stack, and 2 is on the top of 1, in this situation, 1 can not be popped before 2.
Notice
The number of elements does not exceed 1000
解法1:
用一个stack,挨个将push序列push到stack中。用一个指针pointer指向pop序列的最开头。每次push后看1)stack是否为空;2) 若非空则看stack的top元素是否和pop序列的pointer指向元素相等。若相等,则pop出该top元素,并将pointer元素后移。该操作不断循环,直到stack为空或stack的top元素与pop序列的pointer指向元素不相等。然后再将push序列的下一个元素push到stack中。
最后如果stack为空,则为合法pop序列,否则为非法。
代码如下:
class Solution {
public:
/**
* @param push: the array push
* @param pop: the array pop
* @return: return whether there are legal sequences
*/
bool isLegalSeq(vector<int> &push, vector<int> &pop) {
int m = push.size();
int n = pop.size();
if (m != n) return false;
if (n == 0) return true;
stack<int> st;
int index = 0; // index is for arr, num is from [1,2,3,...]
for (int i = 0; i < n; ++i) {
st.push(push[i]);
while(!st.empty() && st.top() == pop[index]) {
st.pop();
index++;
}
}
if (!st.empty()) return false;
return true;
}
};
解法2:TBD