LeetCode Solutions
856. Score of Parentheses
Time: $O(n)$ Space: $O(1)$
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;
}
};
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;
}
}
class Solution:
def scoreOfParentheses(self, S: str) -> int:
ans = 0
layer = 0
for a, b in zip(S, S[1:]):
if a + b == '()':
ans += 1 << layer
layer += 1 if a == '(' else -1
return ans