当前位置:网站首页>Maximum nesting depth of parentheses in leetcode simple questions

Maximum nesting depth of parentheses in leetcode simple questions

2022-07-06 15:04:00 ·Starry Sea

subject

If the string meets one of the following conditions , It can be called Valid bracket string (valid parentheses string, I could just write it as VPS):
The string is an empty string “”, Or a not for “(” or “)” The single character of .
The string can be written as AB(A And B String connection ), among A and B All are Valid bracket string .
The string can be written as (A), among A It's a Valid bracket string .
Similarly , You can define any valid parenthesis string S Of Nesting depth depth(S):
depth("") = 0
depth = 0, among C Is a single character string , And the character is not “(” perhaps “)”
depth(A + B) = max(depth(A), depth(B)), among A and B All are Valid bracket string
depth("(" + A + “)”) = 1 + depth(A), among A It's a Valid bracket string
for example :""、"()()"、"()(()())" All are Valid bracket string ( The nesting depth is 0、1、2), and “)(” 、"(()" Are not Valid bracket string .
To give you one Valid bracket string s, Returns the of the string s Nesting depth .
Example 1:
Input :s = “(1+(23)+((8)/4))+1"
Output :3
explain : Numbers 8 In the nested 3 Layer in parentheses .
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
Tips :
1 <= s.length <= 100
s By digital 0-9 And character ‘+’、’-’、’*’、’/’、’(’、’)’ form
Title Data guarantee bracket expression s yes Valid parenthesis expression
source : Power button (LeetCode)

Their thinking

   Traversing the entire string , Add parentheses on one side only ’(‘ or ’)' And update the maximum depth . In addition, because the given string in the title has been guaranteed to be a valid kueha expression , So we don't need to update the maximum depth every time we accumulate parentheses , The maximum depth can be updated only when the opposite bracket is encountered .

class Solution:
    def maxDepth(self, s: str) -> int:
        MAX=0
        count=0
        for i in s:
            if i=='(':
                count+=1
            elif i==')':
                if MAX<count:
                    MAX=count
                count-=1
        return MAX

 Insert picture description here

原网站

版权声明
本文为[·Starry Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131327152947.html

随机推荐