001.合法的出栈序列
1.直接判定出栈序列是否合法
入栈序列的每一个元素都会入栈依一次,对比栈顶元素既可以得到出栈的时机,若元素不能全部出栈,该序列自然是不合法的
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int>st;
int n = pushed.size();
for(int i = 0,j = 0 ; i < n ; i ++){
st.push(pushed[i]);
while(!st.empty() && st.top() == popped[j]){
st.pop();
j++;
}
}
return st.empty();
}
};
2.限定栈的深度\((M)\)
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped,int M) {
stack<int>st;
int siz = 0;
int n = pushed.size();
for(int i = 0,j = 0 ; i < n ; i ++){
st.push(pushed[i]);
siz++;
if(siz > M) return false;
while(!st.empty() && st.top() == popped[j]){
st.pop();
j++;
siz--;
}
}
return st.empty();
}
};
3.求栈的最小深度
2.中的siz变量已经实现这一功能,不再赘述

浙公网安备 33010602011771号