forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
47 lines (37 loc) · 1.01 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/// Source : https://leetcode.com/problems/validate-stack-sequences/
/// Author : liuyubobobo
/// Time : 2018-11-24
#include <iostream>
#include <vector>
#include <stack>
#include <unordered_set>
using namespace std;
/// Using a stack to simulation
/// and using a HashSet to record every elements
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
unordered_set<int> set;
stack<int> stack;
int i = 0;
for(int e: pushed){
stack.push(e);
set.insert(e);
while(i < popped.size() && !stack.empty() && popped[i] == stack.top()){
stack.pop();
set.erase(e);
i ++;
}
if(i < popped.size() && !stack.empty()
&& popped[i] != stack.top() && set.count(popped[i]))
return false;
}
return stack.empty();
}
};
int main() {
return 0;
}