Problem Description
Explanation:
To solve this problem, we can use a stack to keep track of the scores as we iterate through the input string. We will maintain a variable cur
to store the score of the current frame. When we encounter a (
, we push the current score cur
onto the stack and reset cur
to 0. When we encounter a )
, we calculate the score for the current frame. If the previous character was a (
, then the score for the current frame is 1
. Otherwise, the score is 2 * cur
. We add this score to the top of the stack (if it exists) and update cur
to be the sum of the current score and the score from the stack.
Time Complexity:
The time complexity of this approach is O(n) where n is the length of the input string s
.
Space Complexity:
The space complexity is also O(n) as we are using a stack to store intermediate scores.
:
Solutions
class Solution {
public int scoreOfParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int cur = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(cur);
cur = 0;
} else {
cur = stack.pop() + Math.max(1, 2 * cur);
}
}
return cur;
}
}
Related LeetCode Problems
Loading editor...