euisblue
1614. Maximum Nesting Depth of the Parentheses

C++

1/** 2 * Runtime: 0 ms, faster than 100.00% 3 * Memory Usage: 6.5 MB, less than 22.49% 4 */ 5class Solution { 6 public: 7 int maxDepth(string s) { 8 int max = 0; 9 int cnt = 0; 10 11 for(int i=0; i<s.size(); ++i) 12 { 13 if (s[i] == '(') 14 { 15 ++cnt; 16 } 17 else if (s[i] == ')') 18 { 19 --cnt; 20 } 21 22 if (cnt > max) 23 max = cnt; 24 } 25 26 return max; 27 } 28};

JavaScript

1/** 2 * Runtime: 88 ms, faster than 23.24% 3 * Memory Usage: 38.4 MB, less than 92.83% 4 */ 5var maxDepth = function(s) { 6 let cnt = 0 7 let max = 0 8 9 for (let i=0; i<s.length; ++i) { 10 if (s[i] == '(') ++cnt; 11 else if(s[i] == ')') --cnt; 12 13 max = (cnt > max) ? cnt : max; 14 } 15 16 return max; 17};

Ruby

1# Runtime: 48 ms, faster than 94.92% 2# Memory Usage: 209.9 MB, less than 64.41% 3def max_depth(s) 4 max = 0 5 cnt = 0 6 7 for i in (0...s.size) do 8 if s[i] == '(' 9 cnt += 1 10 elsif s[i] == ')' 11 cnt -= 1 12 end 13 14 max = (cnt > max) ? cnt : max 15 end 16 max 17end