有效括号的嵌套深度。题意是给一个用字符串表示的嵌套括号,请按规则返回这个字符串的嵌套深度depth。嵌套深度的定义如下,
depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, whereA
andB
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, whereA
is a VPS.
例子,
Example 1:
Input: seq = "(()())" Output: [0,1,1,1,1,0]Example 2:
Input: seq = "()(())()" Output: [0,0,0,1,1,0,1,1]
这个题需要用到栈,跟20题类似,需要通过判断遍历的是左括号还是右括号来判断深度。
维护一个栈 s,从左至右遍历括号字符串中的每一个字符:
如果当前字符是 (,就把 ( 压入栈中,此时这个 ( 的嵌套深度为栈的高度;
如果当前字符是 ),此时这个 ) 的嵌套深度为栈的高度,随后再从栈中弹出一个 (。
作者:LeetCode-Solution
链接: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/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间O(n)
空间O(n)
Java实现
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实现
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 };
来源:https://www.cnblogs.com/aaronliu1991/p/12610065.html