Leetcode 1111. Maximum Nesting Depth of Two Valid Parentheses Strings解题报告(python)

本文探讨了一种有效的方法来划分括号字符串,以达到最小化最大深度的目标。通过交替分配连续的左括号到两个子集,确保了深度的均匀分布,从而降低了最大深度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1111. Maximum Nesting Depth of Two Valid Parentheses Strings

  1. Maximum Nesting Depth of Two Valid Parentheses Strings python solution

题目描述

A string is a valid parentheses string (denoted VPS) if and only if it consists of “(” and “)” characters only, and:
It is the empty string, 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 seq, split it into two disjoint subsequences A and B, such that A and B are VPS’s (and A.length + B.length = seq.length)
Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.
Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them.

在这里插入图片描述

解析

这个题目本身难度不大,但是比较难以理解。所以解题的关键在于理解题目要表达的意思。
首先分析题目中给的几个例子 “”, “()()”, “()(()())” 都是VPS分别对应深度为 (0, 1, 2)。

那么"(())()" 可以被分成 A = “(())” and B = “()“两个集合,此时depth=max(depth(A), depth(B))=max(2,1)=2
但根据题目要求,希望得到一个最小的max(depth(A), depth(B)),所以上述例子不能满足这个要求。
另一种分割方法,可以将”(())()” 分成A = ()() and B = (),此时depth=max(depth(A), depth(B))=max(1,1)=1
所以求得最小的depth关键在于如何分配‘((()))()()()()‘中的’((()))’,也就是处理连续出现同一符号的情况。
其实处理起来也十分简单,连续出现左括号时,我们将其交替分配给A,B两个集合,尽量分散depth。直到遇到右括号,将其分配给左括号多的那个集合。

// An highlighted block
class Solution:
    def maxDepthAfterSplit(self, seq: str) -> List[int]:
        ans=[]
        count=0
        for i in seq:
            if i=='(':count+=1
            ans.append(count%2)
            if i==')':count-=1
        return ans          

Reference

https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/358419/Confused-by-this-problem-I-was-too-but-here-is-how-it-became-crystal-clear…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值