Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4e5346d

Browse files
author
konstantin
committed
Medium946 challenge
1 parent 0cf66ff commit 4e5346d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /