LeetCode 5535. Maximum nesting depth of parentheses

Article Directory

1. Title

If the bit string satisfies one of the conditions, may be called active brackets string (valid parentheses string, may be abbreviated as VPS):

  • Empty string is a string "", or is not a "(" 或 ")"single character.
  • The string can be written as AB (A and B are concatenated), where A and B are both valid parenthesized strings.
  • The string can be written as (A), where A is a valid bracketed string.

Similarly, the nesting depth depth(S) of any valid bracket string S can be defined:

  • depth("") = 0
  • depth(A + B) = max(depth(A), depth(B)), Where A and B are both valid parenthesized strings
  • depth("(" + A + ")") = 1 + depth(A), Where A is a valid bracketed string

For example: ""、"()()"、"()(()())"all active brackets string (0,1,2 nesting depth, respectively), but ")(" 、"(()"not a valid string brackets.

Gives you a valid parenthesized string s, and returns the s nesting depth of the string .

示例 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 <= 100
s 由数字 0-9 和字符 '+''-''*''/''('')' 组成
题目数据保证括号表达式 s 是 有效的括号表达式

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/maximum-nesting-depth-of-the-parentheses The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

2. Problem solving

  • Meet the left parenthesis ++, meet the right parenthesis--
class Solution {
    
    
public:
    int maxDepth(string s) {
    
    
        int maxdepth = 0, deep = 0;
        for(char c : s)
        {
    
    
            if(c == '(')
                deep++;
            else if(c == ')')
                deep--;
            maxdepth = max(maxdepth, deep);
        }
        return maxdepth;
    }
};

4 ms 5.9 MB


My CSDN blog address https://michael.blog.csdn.net/

Long press or scan the code to follow my official account (Michael Amin), cheer together, learn and progress together!
Michael Amin

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/109011780