-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.kt
More file actions
41 lines (32 loc) · 923 Bytes
/
ValidParentheses.kt
File metadata and controls
41 lines (32 loc) · 923 Bytes
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
package leetcode
import java.util.*
/**
* Problem description on [LeetCode](https://leetcode.com/problems/valid-parentheses/)
*/
class ValidParentheses {
private val parentheses = mapOf(
')' to '(',
'}' to '{',
']' to '['
)
fun isValid(s: String): Boolean {
val stack = Stack<Char>()
s.forEach { ch ->
when {
isOpenParentheses(ch) ->
stack.push(ch)
isCloseParentheses(ch) -> {
if (stack.isEmpty()) return false
if (parentheses[ch] != stack.pop()) return false
}
}
}
return stack.isEmpty()
}
private fun isOpenParentheses(ch: Char): Boolean {
return parentheses.values.contains(ch)
}
private fun isCloseParentheses(ch: Char): Boolean {
return parentheses.keys.contains(ch)
}
}