@@ -45,16 +45,14 @@ push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
45
45
``` python
46
46
class Solution :
47
47
def validateStackSequences (self , pushed : List[int ], popped : List[int ]) -> bool :
48
- t = []
49
- for num in popped:
50
- while len (t) == 0 or t[- 1 ] != num:
51
- if len (pushed) == 0 :
52
- return False
53
- t.append(pushed[0 ])
54
- pushed = pushed[1 :]
55
- t.pop()
56
- return True
57
-
48
+ s = []
49
+ q = 0
50
+ for num in pushed:
51
+ s.append(num)
52
+ while s and s[- 1 ] == popped[q]:
53
+ s.pop()
54
+ q += 1
55
+ return not s
58
56
```
59
57
60
58
### ** Java**
@@ -64,18 +62,16 @@ class Solution:
64
62
``` java
65
63
class Solution {
66
64
public boolean validateStackSequences (int [] pushed , int [] popped ) {
67
- Stack<Integer > t = new Stack<> ();
68
- int i = 0 , n = pushed. length;
69
- for (int num : popped) {
70
- while (t. empty() || t. peek() != num) {
71
- if (i == n) {
72
- return false ;
73
- }
74
- t. push(pushed[i++ ]);
65
+ Deque<Integer > s = new ArrayDeque<> ();
66
+ int q = 0 ;
67
+ for (int num : pushed) {
68
+ s. push(num);
69
+ while (! s. isEmpty() && s. peek() == popped[q]) {
70
+ s. pop();
71
+ ++ q;
75
72
}
76
- t. pop();
77
73
}
78
- return true ;
74
+ return s . isEmpty() ;
79
75
}
80
76
}
81
77
```
@@ -88,25 +84,17 @@ class Solution {
88
84
* @param {number[]} popped
89
85
* @return {boolean}
90
86
*/
91
- var validateStackSequences = function (pushed , popped ) {
92
- let stack = [];
93
- while (pushed .length && popped .length ) {
94
- if (pushed[0 ] === popped[0 ]) {
95
- pushed .shift ();
96
- popped .shift ();
97
- } else if (popped[0 ] === stack[0 ]) {
98
- stack .shift ();
99
- popped .shift ();
100
- } else {
101
- stack .unshift (pushed .shift ());
87
+ var validateStackSequences = function (pushed , popped ) {
88
+ let s = [];
89
+ let q = 0 ;
90
+ for (let num of pushed) {
91
+ s .push (num);
92
+ while (s .length > 0 && s[s .length - 1 ] == popped[q]) {
93
+ ++ q;
94
+ s .pop ();
95
+ }
102
96
}
103
- }
104
- while (stack .length ) {
105
- if (stack[0 ] !== popped[0 ]) return false ;
106
- stack .shift ();
107
- popped .shift ();
108
- }
109
- return true ;
97
+ return s .length == 0 ;
110
98
};
111
99
```
112
100
0 commit comments