LeetCode in Kotlin

1614. Maximum Nesting Depth of the Parentheses

Easy

A string is a valid parentheses string (denoted VPS) if it meets one of the following:

We can similarly define the nesting depth depth(S) of any VPS S as follows:

For example, "", "()()", and "()(()())" are VPS’s (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS’s.

Given a VPS represented as string s, return the nesting depth of s.

Example 1:

Input: s = “(1+(2*3)+((8)/4))+1”

Output: 3

Explanation: Digit 8 is inside of 3 nested parentheses in the string.

Example 2:

Input: s = “(1)+((2))+(((3)))”

Output: 3

Constraints:

Solution

import java.util.Deque
import java.util.LinkedList

class Solution {
    fun maxDepth(s: String): Int {
        val stack: Deque<Char> = LinkedList()
        var maxDepth = 0
        for (c in s.toCharArray()) {
            if (c == '(') {
                stack.push(c)
            } else if (c == ')') {
                maxDepth = maxDepth.coerceAtLeast(stack.size)
                stack.pop()
            }
        }
        return maxDepth
    }
}