LeetCode 856: Score of Parentheses Solution
Master LeetCode problem 856 (Score of Parentheses), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 856 (Score of Parentheses)?
This page provides optimized solutions for LeetCode problem 856 (Score of Parentheses) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 856 (Score of Parentheses)?
The time complexity for LeetCode 856 (Score of Parentheses) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 856 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 856 in Java, C++, or Python.