1
+ package medium
2
+
3
+ import ArraysTopic
4
+ import StackTopic
5
+ import java.util.*
6
+
7
+ /* *
8
+ * 946. Validate Stack Sequences
9
+ * https://leetcode.com/problems/validate-stack-sequences/
10
+ *
11
+ Given two integer arrays pushed and popped each with distinct values,
12
+ return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
13
+ */
14
+
15
+ class Medium946 : ArraysTopic , StackTopic {
16
+
17
+ fun validateStackSequences (pushed : IntArray , popped : IntArray ): Boolean {
18
+ val stack = Stack <Int >()
19
+ var i = 0
20
+ var j = 0
21
+ while (i < pushed.size || j < popped.size) {
22
+ if (stack.isEmpty()) {
23
+ if (i < pushed.size) {
24
+ stack.push(pushed[i])
25
+ i++
26
+ } else return false
27
+ } else {
28
+ if (j < popped.size) {
29
+ if (popped[j] == stack.peek()) {
30
+ stack.pop()
31
+ j++
32
+ } else {
33
+ if (i < pushed.size) {
34
+ stack.push(pushed[i])
35
+ i++
36
+ } else return false
37
+ }
38
+ } else return false
39
+ }
40
+ }
41
+ return true
42
+ }
43
+ }
44
+
45
+ fun main () {
46
+ println (Medium946 ().validateStackSequences(intArrayOf(1 , 2 , 3 , 4 , 5 ), intArrayOf(4 , 5 , 3 , 2 , 1 )))
47
+ println (Medium946 ().validateStackSequences(intArrayOf(1 , 2 , 3 , 4 , 5 ), intArrayOf(4 , 3 , 5 , 1 , 2 )))
48
+
49
+ }
0 commit comments