題目講解
946. 驗證棧序列
算法講解
在這里就只需要模擬一下這個棧的出棧順序即可:使用一個stack,每次讓pushed里面的元素入棧,如果當前棧頂的元素等于poped容器中的當前元素,因此就需要讓棧頂元素出棧,poped的遍歷位置往后移動一位
class Solution {
public:bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {stack<int>st;int i = 0;for(auto& num : pushed){st.push(num);while(!st.empty() && st.top() == popped[i]){st.pop();i++;}}return st.empty();}
};