原文链接: https://leetcode-cn.com/problems/maximum-nesting-depth-of-the-parentheses
英文原文
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(Aconcatenated withB), whereAandBare VPS's, or - It can be written as
(A), whereAis a VPS.
We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0depth(C) = 0, whereCis a string with a single character not equal to"("or")".depth(A + B) = max(depth(A), depth(B)), whereAandBare VPS's.depth("(" + A + ")") = 1 + depth(A), whereAis 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)+((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
Example 3:
Input: s = "1+(2*3)/(2-1)" Output: 1
Example 4:
Input: s = "1" Output: 0
Constraints:
1 <= s.length <= 100sconsists of digits0-9and characters'+','-','*','/','(', and')'.- It is guaranteed that parentheses expression
sis a VPS.
中文题目
如果字符串满足以下条件之一,则可以称之为 有效括号字符串(valid parentheses string,可以简写为 VPS):
- 字符串是一个空字符串
"",或者是一个不为"("或")"的单字符。 - 字符串可以写为
AB(A与B字符串连接),其中A和B都是 有效括号字符串 。 - 字符串可以写为
(A),其中A是一个 有效括号字符串 。
类似地,可以定义任何有效括号字符串 S 的 嵌套深度 depth(S):
depth("") = 0depth(C) = 0,其中C是单个字符的字符串,且该字符不是"("或者")"depth(A + B) = max(depth(A), depth(B)),其中A和B都是 有效括号字符串depth("(" + A + ")") = 1 + depth(A),其中A是一个 有效括号字符串
例如:""、"()()"、"()(()())" 都是 有效括号字符串(嵌套深度分别为 0、1、2),而 ")(" 、"(()" 都不是 有效括号字符串 。
给你一个 有效括号字符串 s,返回该字符串的 s 嵌套深度 。
示例 1:
输入:s = "(1+(2*3)+((8)/4))+1" 输出:3 解释:数字 8 在嵌套的 3 层括号中。
示例 2:
输入:s = "(1)+((2))+(((3)))" 输出:3
示例 3:
输入:s = "1+(2*3)/(2-1)" 输出:1
示例 4:
输入:s = "1" 输出:0
提示:
1 <= s.length <= 100s由数字0-9和字符'+'、'-'、'*'、'/'、'('、')'组成- 题目数据保证括号表达式
s是 有效的括号表达式
通过代码
高赞题解
- 使用
depth变量表示括号的深度,使用max变量记录depth的最大值。 - 遍历字符串中的字符
- 遇到
(,depth加1,更新最大值 - 遇到
),depth减1
- 返回
max。public int maxDepth(String s) { //括号的深度 int depth = 0; //最大深度 int max = 0; for (char c : s.toCharArray()) { if (c == '(') { //深度加1 depth++; //更新最大值 max = Math.max(depth, max); } else if (c == ')') { //深度减1 depth--; } } return max; }
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 17824 | 21703 | 82.1% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|