[leetcode] valid parentheses in kotlin

최대한·2023년 9월 16일

https://leetcode.com/problems/valid-parentheses/description/

fun valid_parentheses(s: String): Boolean {
    if (s.length / 2 == 1) return false
    when(s[0]) {
        ')', '}', ']' -> return false
    }

    val stack = Stack<Char>()
    s.forEach { c ->
        when (c) {
            '(', '{', '[' -> stack.add(c)
            ')', '}', ']' -> {
                if (stack.size == 0) return false
                val p = when(c) {
                    ')' -> '('
                    '}' -> '{'
                    ']' -> '['
                    else -> throw Exception()
                }
                if (stack.pop() != p) return false
            }
        }
    }
    return stack.size == 0
}
profile
Awesome Dev!

0개의 댓글