# 946. Validate Stack Sequences 验证栈序列

@TOC

## # 题目描述

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:

1. 0 <= pushed.length == popped.length <= 1000
2. 0 <= pushed[i], popped[i] < 1000
3. pushed is a permutation of popped.
4. pushed and popped have distinct values.

## # 解题方法

### # 模拟过程

class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
stack = []
N = len(pushed)
pi = 0
for i in range(N):
if stack and popped[i] == stack[-1]:
stack.pop()
else:
while pi < N and pushed[pi] != popped[i]:
stack.append(pushed[pi])
pi += 1
pi += 1
return not stack

class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
bool canbe = true;
int N = pushed.size();
stack<int> s;
int pi = 0;
for (int i = 0; i < N; i++) {
s.push(pushed[i]);
while (!s.empty() && s.top() == popped[pi]) {
s.pop();
pi++;
}
}
return s.empty();
}
};

## # 日期

2018 年 11 月 24 日 —— 周日开始！一周就过去了～ 2018 年 12 月 7 日 —— 恩，12月又过去一周了