|
| 1 | +/** |
| 2 | + * 1111. Maximum Nesting Depth of Two Valid Parentheses Strings |
| 3 | + * https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" |
| 7 | + * characters only, and: |
| 8 | + * - It is the empty string, or |
| 9 | + * - It can be written as AB (A concatenated with B), where A and B are VPS's, or |
| 10 | + * - It can be written as (A), where A is a VPS. |
| 11 | + * |
| 12 | + * We can similarly define the nesting depth depth(S) of any VPS S as follows: |
| 13 | + * - depth("") = 0 |
| 14 | + * - depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's |
| 15 | + * - depth("(" + A + ")") = 1 + depth(A), where A is a VPS. |
| 16 | + * |
| 17 | + * For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), |
| 18 | + * and ")(" and "(()" are not VPS's. |
| 19 | + * |
| 20 | + * Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's |
| 21 | + * (and A.length + B.length = seq.length). |
| 22 | + * |
| 23 | + * Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. |
| 24 | + * |
| 25 | + * Return an answer array (of length seq.length) that encodes such a choice of A and B: |
| 26 | + * answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple |
| 27 | + * answers may exist, you may return any of them. |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {string} seq |
| 32 | + * @return {number[]} |
| 33 | + */ |
| 34 | +var maxDepthAfterSplit = function(seq) { |
| 35 | + const result = new Array(seq.length); |
| 36 | + let depth = 0; |
| 37 | + |
| 38 | + for (let i = 0; i < seq.length; i++) { |
| 39 | + if (seq[i] === '(') { |
| 40 | + result[i] = depth++ % 2; |
| 41 | + } else { |
| 42 | + result[i] = --depth % 2; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return result; |
| 47 | +}; |
0 commit comments