Skip to content

856. Score of Parentheses 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int scoreOfParentheses(string s) {
    int ans = 0;
    int layer = 0;

    for (int i = 0; i + 1 < s.length(); ++i) {
      const char a = s[i];
      const char b = s[i + 1];
      if (a == '(' && b == ')')
        ans += 1 << layer;
      layer += a == '(' ? 1 : -1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int scoreOfParentheses(String s) {
    int ans = 0;
    int layer = 0;

    for (int i = 0; i + 1 < s.length(); ++i) {
      final char a = s.charAt(i);
      final char b = s.charAt(i + 1);
      if (a == '(' && b == ')')
        ans += 1 << layer;
      layer += a == '(' ? 1 : -1;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def scoreOfParentheses(self, s: str) -> int:
    ans = 0
    layer = 0

    for a, b in itertools.pairwise(s):
      if a + b == '()':
        ans += 1 << layer
      layer += 1 if a == '(' else -1

    return ans