1111. Maximum Nesting Depth of Two Valid Parentheses Strings
- 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…