1111. Maximum Nesting Depth of Two Valid Parentheses Strings 解題紀錄

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 VPSseq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length). The subsequences may not necessarily be contiguous. For example, for the sequence 123456789, one possible split is: A = {1, 3, 5, 7, 9}, B = {2, 4, 6, 8}. This corresponds to the output [0, 1, 0, 1, 0, 1, 0, 1, 0]  where 0 indicates membership in A and 1 indicates membership in B. 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.   Example 1: Input: seq = "(()())" Output: [0,1,1,1,1,0] Example 2: Input: seq = "()(())()" Output: [0,0,0,1,1,0,1,1]   Constraints: 1 <= seq.size <= 10000 今天這題給我們一個字串 seq, seq 裡面只有包含 () 兩個字元, 題目希望我們用兩組索引分別計算, 希望最小化 () 的層級。 題目希望我們回傳最佳化分配索引的組合。 這題我原本看不太懂題目, 但最小化階層其實就是要盡量讓括號嵌套這件事情少發生; 少發生的方法就是相鄰上下層都分給不同索引, 這樣假設最深層為 D,最深層都可以拆到變成 D/2 + 1。 C++程式碼:
megapx
假設 seq 的長度為 N。 計算複雜度:O(N) 空間複雜度:O(N) Github程式碼:
愛心
3
留言
encourage first comment
有些話想說嗎 快分享出來彼此交流吧!