Given two sequences pushed
and popped
with distinct values, return true
if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Note:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed
is a permutation ofpopped
.pushed
andpopped
have distinct values.
這道題給了兩個序列 pushed 和 popped,讓判斷這兩個序列是否能表示同一個棧的壓入和彈出操作,由於棧是后入先出的順序,所以並不是任意的兩個序列都是滿足要求的。比如例子2中,先將 1,2,3,4 按順序壓入棧,此時4和3出棧,接下來壓入5,再讓5出棧,接下來出棧的是2而不是1,所以例子2會返回 false。而這道題主要就是模擬這個過程,使用一個棧,和一個變量i用來記錄彈出序列的當前位置,此時遍歷壓入序列,對遍歷到的數字都壓入棧,此時要看彈出序列當前的數字是否和棧頂元素相同,相同的話就需要移除棧頂元素,並且i自增1,若下一個棧頂元素還跟新位置上的數字相同,還要進行相同的操作,所以用一個 while 循環來處理。直到最終遍歷完壓入序列后,若此時棧為空,則說明是符合題意的,否則就是 false,參見代碼如下:
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> st;
int i = 0;
for (int num : pushed) {
st.push(num);
while (!st.empty() && st.top() == popped[i]) {
st.pop();
++i;
}
}
return st.empty();
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/946
參考資料:
https://leetcode.com/problems/validate-stack-sequences/