From cc2f4366445cb7d1b7ce63f448f17b5b47ea2657 Mon Sep 17 00:00:00 2001 From: Edoardo Cecchinato <72577095+edo-ce@users.noreply.github.com> Date: Thu, 21 Jul 2022 12:51:40 +0200 Subject: [PATCH] Kotlin 20-Valid-Parentheses.kt --- kotlin/20-Valid-Parentheses.kt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 kotlin/20-Valid-Parentheses.kt diff --git a/kotlin/20-Valid-Parentheses.kt b/kotlin/20-Valid-Parentheses.kt new file mode 100644 index 000000000..163f36d54 --- /dev/null +++ b/kotlin/20-Valid-Parentheses.kt @@ -0,0 +1,16 @@ +class Solution { + fun isValid(s: String): Boolean { + if (s.length % 2 == 1) return false + + val map = hashMapOf('(' to ')', '[' to ']', '{' to '}') + val stack = Stack() + + for (c in s) { + if (map.containsKey(c)) + stack.push(c) + else if (stack.isEmpty() || map[stack.pop()] != c) + return false + } + return stack.isEmpty() + } +}