Score of Parentheses

medium string stack

Problem

Given a balanced parentheses string, compute its score: () = 1, AB = A + B, (A) = 2 · A.

Inputs = "(()(()))"
Output6
Two "()" atoms at depths 2 and 3 contribute 2 + 4 = 6.

def scoreOfParentheses(s):
    depth = 0
    score = 0
    for i, c in enumerate(s):
        if c == '(':
            depth += 1
        else:
            depth -= 1
            if s[i - 1] == '(':
                score += 1 << depth
    return score
function scoreOfParentheses(s) {
  let depth = 0, score = 0;
  for (let i = 0; i < s.length; i++) {
    if (s[i] === '(') depth++;
    else {
      depth--;
      if (s[i - 1] === '(') score += 1 << depth;
    }
  }
  return score;
}
class Solution {
    public int scoreOfParentheses(String s) {
        int depth = 0, score = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') depth++;
            else {
                depth--;
                if (s.charAt(i - 1) == '(') score += 1 << depth;
            }
        }
        return score;
    }
}
int scoreOfParentheses(string s) {
    int depth = 0, score = 0;
    for (int i = 0; i < (int)s.size(); i++) {
        if (s[i] == '(') depth++;
        else {
            depth--;
            if (s[i - 1] == '(') score += 1 << depth;
        }
    }
    return score;
}
Time: O(n) Space: O(1)