[LeetCode] 1111. Maximum Nesting Depth of Two Valid Parentheses Strings

Effective parentheses nesting depth. Meaning of the questions is to give a nested parentheses represented by the string, the string returned by the rules of the depth of nesting depth. Nesting depth is defined 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.

example,

Example 1:

Input: seq = "(()())"
Output: [0,1,1,1,1,0]

Example 2:

Input: seq = "()(())()"
Output: [0,0,0,1,1,0,1,1]

This problem need to use the stack, with 20 questions Similarly, the need to determine the depth is traversed by a judge or a left parenthesis right parenthesis.

Maintaining a stack s, traversing from left to right in parentheses in each character string:

If the current character is a (, put (pushed onto the stack, in this case (the nesting depth is the height of the stack;

If the current character is), this case) nesting depth of the stack height, and subsequently popped from a stack (.

 

Author: LeetCode-Solution
link: https: //leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/solution/you-xiao-gua-hao-de-qian-tao -shen-du-by-leetcode- s /
source: stay button (LeetCode)
copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Time O (n)

Space O (n)

Java implementation

 1 class Solution {
 2     public int[] maxDepthAfterSplit(String seq) {
 3         if (seq == null || seq.isEmpty()) {
 4             return new int[0];
 5         }
 6         int[] res = new int[seq.length()];
 7         Stack<Integer> stack = new Stack<>();
 8         for (int i = 0; i < seq.length(); i++) {
 9             if (seq.charAt(i) == '(') {
10                 stack.push(i);
11             } else {
12                 int depth = stack.size();
13                 int left = stack.pop();
14                 if (depth % 2 == 0) {
15                     res[left] = 1;
16                     res[i] = 1;
17                 }
18             }
19         }
20         return res;
21     }
22 }

 

JavaScript implementation

 1 /**
 2  * @param {string} seq
 3  * @return {number[]}
 4  */
 5 var maxDepthAfterSplit = function(seq) {
 6     // corner case
 7     if (seq == null || seq.length == 0) {
 8         return [0];
 9     }
10 
11     // normal case
12     let res = new Array(seq.length).fill(0);
13     let stack = [];
14     for (let i = 0; i < seq.length; i++) {
15         let c = seq.charAt(i);
16         if (c == '(') {
17             stack.push(i);
18         } else {
19             let depth = stack.length;
20             let left = stack.pop();
21             if (depth % 2 == 0) {
22                 res[left] = 1;
23                 res[i] = 1;
24             }
25         }
26     }
27     return res;
28 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12610065.html