# LeetCode 1614. Maximum Nesting Depth of the Parentheses【String】簡單 A string is a valid parentheses string (denoted VPS) if it meets one of the following: * It is an empty string "", or a single character not equal to "(" or ")", * It can be written as AB (A concatenated with B), where A and B are VPS's, or * It can be written as (A), where A is a VPS. We can similarly define the nesting depth depth(S) of any VPS S as follows: * depth("") = 0 * depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's * depth("(" + A + ")") = 1 + depth(A), where A is a VPS. 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)+((<u>8</u>)/4))+1" Output: 3 Explanation: Digit 8 is inside of 3 nested parentheses in the string. ``` **Example 2:** ``` Input:s = "(1)+((2))+(((<u>3</u>)))" Output: 3 ``` **解法** **我們只需要知道VPS任一個字串的深度等於它之前的左括號個數 - 右括號個數 這樣即可。** JAVA ```{java} class Solution { public int maxDepth(String s) { Stack<Character> stack = new Stack<>(); char[] ch = s.toCharArray(); int maxLevel = 0; for (char c: ch){ if (c == '(') stack.add(c); else if (c == ')') stack.pop(); int size = stack.size(); maxLevel = Math.max(maxLevel, size); } return maxLevel; } } ```